在Android中单击按钮时显示/隐藏片段

时间:2016-09-20 10:25:20

标签: android android-fragments

我想知道如何在Android中的按钮点击中显示和隐藏片段。当按钮处于单击状态时,则应显示片段,当再次单击该按钮时,片段应该消失。

3 个答案:

答案 0 :(得分:0)

您应该使用Dialog片段来实现此目的。 Dialog Fragment具有片段所具有的所有生命周期,并具有对话框等行为。 例如要显示,只需调用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();

希望这会对你有帮助!

答案 1 :(得分:0)

片段交易的内部显示/隐藏标志会有所帮助。

FragmentManager fm = getFragmentManager();
fm.beginTransaction()
          .setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
          .show(somefrag) //or hide(somefrag)
          .commit();

答案 2 :(得分:0)

我试过这个,它对我有用。首先,我在第一次点击按钮时添加了片段,然后在我附加的后续点击中添加了片段并将其分离。所以它创建了片段,然后没有破坏它只显示并隐藏它。

这是代码....首次创建MainActivity时,count最初为0

       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();
        }

    }
相关问题