按钮触摸删除片段

时间:2016-09-02 13:39:01

标签: android android-fragments

我需要在点击其中的按钮时删除片段

public static class EditNameDialog extends DialogFragment {
    ...
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_find_in_page, container);
        ...
        Button cancelButton = (Button) view.findViewById(R.id.cancel_button);
        cancelButton.setOnTouchListener(new View.OnTouchListener()
        {
            public boolean onTouch(View arg0, MotionEvent arg1) {
                //remove the fragment here
                return false;
            }
        });
        return view;
    }
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        ...
    }
}

我只需要在点击按钮时删除片段

1 个答案:

答案 0 :(得分:3)

您可以使用以下代码删除片段:

 //remove the fragment from transaction manager
    FragmentManager frgManager = getSupportFragmentManager();
    Fragment fragment = frgManager.findFragmentByTag(tagName);
    if (fragment != null) {
        FragmentTransaction ft = frgManager.beginTransaction();
        ft.remove(fragment).commit();
    }