Reputation: 21
I want to know how to show and hide a fragment on a button click in Android. When button is in clicked state then fragment should appear, and when the button is clicked again then the fragment should disappear.
Upvotes: 0
Views: 5652
Reputation: 26
I tried this and it worked for me. First I added the fragment when button is clicked for first time and then on subsequent clicks I attached and detached it. So it created the fragment and then without destroying it only showed and hid it.
this is the code.... Initially count is 0 when the MainActivity is first created
public void Settings(View view){
if(count==0){
count++;
// add a fragment for the first time
MyFragment frag=new MyFragment();
FragmentTransaction ft=manager.beginTransaction();
ft.add(R.id.group,frag,"A");
ft.commit();
}else{
//check if fragment is visible, if no, then attach a fragment
//else if its already visible,detach it
Fragment frag=manager.findFragmentByTag("A");
if(frag.isVisible() && frag!=null){
FragmentTransaction ft=manager.beginTransaction();
ft.detach(frag);
ft.commit();
}else{
FragmentTransaction ft=manager.beginTransaction();
ft.attach(frag);
ft.commit();
}
}
Upvotes: 1
Reputation: 1323
Fragment Transaction's internal show/hide flag will help.
FragmentManager fm = getFragmentManager();
fm.beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.show(somefrag) //or hide(somefrag)
.commit();
Upvotes: 0
Reputation: 696
You should use Dialog fragment for this purpose. Dialog Fragment has all life cycle as fragment has and has behavior like dialog. For example to show, simply call dialogFragment.show() method, and to hide, call dialogFragment.dismiss() method.
Here is an example how to make a dialog fragment.
public class DialogFragmentExample extends DialogFragment{
@Override
public void onStart() {
super.onStart();
// To make dialog fragment full screen.
Dialog dialog = getDialog();
if (dialog != null) {
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
//
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
return inflater.inflate(R.layout.your_xml_layout, container, false);
}
// initialize your views here
}
And to show this dialog fragment;
DialogFragmentExample fragment = new DialogFragmentExample();
fragment.show();
similarly to dismiss,
fragment.dismiss();
Hope this will help you!
Upvotes: 0