单击该片段中的n按钮时如何替换片段?

时间:2018-01-05 02:33:14

标签: android android-fragments

我有一项活动。在活动中有一个片段持有者。当应用程序运行时,我显示fragment_1。在fragment_1中,我有一个按钮。当我单击该按钮时,片段持有者将更改为fragment_2。

2 个答案:

答案 0 :(得分:0)

试试这个

  1. Fragment1创建名为OnFragment1ActiontListener的公共接口并处理onAttach()中的逻辑

    public class Fragment1 {
    
        OnFragment1ActiontListener mCallback;
    
        // Container Activity must implement this interface
        public interface OnFragment1ActiontListener {
            public void onSwitchToFragment2();
        }
    
        @Override
        public void onAttach(Activity activity) {
           super.onAttach(activity);
           try {
              mCallback = (OnFragment1ActiontListener) activity;
           } catch (ClassCastException e) {
              throw new ClassCastException(activity.toString()
                    + " must implement OnFragment1ActiontListener");
           }
        }
    
        // call this method when you click button
       public void onButtonClicked() {
          mCallback.onSwitchToFragment2();
       }
    }
    
  2. 在您的活动中,实施界面OnFragment1ActiontListener。您需要@Override以下方法

    @Override
    public void onSwitchToFragment2() {
       // use fragmentholder to change to fragment2
      Fragment2 fragment = new Fragment2();
      FragmentTransaction trs = getSupportFragmentManager().beginTransaction();
      trs.replace(R.id.fragmentholder, fragment);
      trs.commit();
    }
    

    希望有所帮助!

答案 1 :(得分:0)

// Create new fragment
Fragment newFragment = new NewFragment();

// Open transaction
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace and add the transaction to the back stack if needed
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();