在Android中按钮上单击显示/隐藏片段
答
我试过这个,它为我工作。首先,我在第一次点击按钮时添加了片段,然后在随后的附加和分离按钮上添加了片段。所以它创建了片段,然后不破坏它只显示并隐藏它。
这是代码....最初计数是0时在MainActivity首次创建
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();
}
}
答
您应该为此使用对话框片段。对话框片段具有片段所具有的所有生命周期,并具有像对话一样的行为。例如要显示,只需调用dialogFragment.show()方法,并隐藏,调用dialogFragment.dismiss()方法。
下面是一个如何制作对话框片段的例子。
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
}
并显示此对话框片段;
DialogFragmentExample fragment = new DialogFragmentExample();
fragment.show();
同样驳回,
fragment.dismiss();
希望这将帮助你!
答
片段交易的内部显示/隐藏标志将有所帮助。
FragmentManager fm = getFragmentManager();
fm.beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.show(somefrag) //or hide(somefrag)
.commit();