简体   繁体   English

Android Backstack的片段功能

[英]Android backstack functioning for fragments

I have written a code where I try to navigate in between fragments 1, 2 ,3 ,4. 我写了一段代码,试图在片段1、2、3、4之间导航。 The navigation is like: 1->2->3->4->2. 导航类似于:1-> 2-> 3-> 4-> 2。

Each fragment has a button whose onClickListener calls the method in interface which is implemented by the mainactivity, wherein position is passed as parameter. 每个片段都有一个按钮,其onClickListener调用由mainactivity实现的接口中的方法,其中位置作为参数传递。

eg onClick on the button in 4th fragment calls the method wherein I pass the position parameter as '2' to call the second fragment. 例如ononClick在第四个片段中的按钮上调用方法,其中我将位置参数传递为“ 2”以调用第二个片段。

Now, I have added the transaction 1->2 to the backstack, Using a backstack name "second". 现在,我使用后堆栈名称“ second”将事务1-> 2添加到了后堆栈。 When, I try to go from 4>2, I use the function popBackStackImmediate("second", 0). 当我尝试从4> 2开始时,我使用函数popBackStackImmediate(“ second”,0)。 But, the boolean response is false and nothing is popped from the stack. 但是,布尔响应为假,并且堆栈中未弹出任何内容。

My questions are : 我的问题是:

  1. Why is popBackStackImmediate returning false? 为什么popBackStackImmediate返回false?
  2. What is the use of second parameter in the same function ie flag ? 在同一函数(即flag)中第二个参数有什么用?
  3. When we add the transaction in the backstack, the transaction is saved and not the fragment. 当我们将事务添加到后堆栈中时,将保存事务,而不是片段。 So, where is the fragment object getting saved actually as the backstack saves the transaction? 那么,片段对象实际上在哪里保存,而后堆栈将保存事务?

The MainActivity in my code is : 我的代码中的MainActivity是:

` `

    public class MainActivity extends AppCompatActivity implements Frag1.OnFragmentInteractionListener, Frag2.OnFragmentInteractionListener, Frag3.OnFragmentInteractionListener, Frag4.OnFragmentInteractionListener {

LinearLayout layout;
Frag1 frag1;
Frag2 frag2;
Frag3 frag3;
Frag4 frag4;
android.support.v4.app.FragmentTransaction transaction;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.i("I", "Main Act");
    layout = (LinearLayout) findViewById(R.id.frag);
    frag1 = Frag1.newInstance();

    transaction = getSupportFragmentManager().beginTransaction();

    // Replace whatever is in the fragment_container view with this fragment,
    // and add the transaction to the back stack so the user can navigate back
    transaction.add(R.id.frag, frag1, "first");
  //  frag1 = Frag1.newInstance();
   // transaction.add(R.id.frag, frag1, "first1");
  //  transaction.add(R.id.frag, frag2, "second");
   // transaction.add(R.id.frag, frag2, "second");
 //  transaction.add(R.id.frag, frag3, "third");
    // Commit the transaction
  //  transaction.add(R.id.frag, frag3, "third");

  //  transaction.replace(R.id.frag, frag2, "second");

    transaction.commit();



}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

// Fragment to activity interface implementation //片段到活动接口的实现

@Override
public void onFragmentInteraction(int pos) {

    if (pos == 2) {
       // Fragment f = getSupportFragmentManager().findFragmentByTag("second");
        FragmentManager manager = getSupportFragmentManager();

        boolean isAvail =  manager.popBackStackImmediate("second", 0);

        if (isAvail) {
           // frag2 = (Frag2) f;
            Log.i("MainAct", "Instance of 2 yes");
        }else{
            transaction = getSupportFragmentManager().beginTransaction();
           frag2 = Frag2.newInstance();
            Log.i("MainAct", "Instance of 2 No");
            transaction.replace(R.id.frag, frag2, "second");
            transaction.addToBackStack("second");
            transaction.commit();
        }



    } else if (pos == 3) {
        Fragment f = getSupportFragmentManager().findFragmentByTag("third");
        transaction = getSupportFragmentManager().beginTransaction();
        if (f instanceof Frag3) {
            frag3 = (Frag3) f;
            Log.i("MainAct", "Instance of 3 yes");
        }else{
            frag3 = Frag3.newInstance();
            Log.i("MainAct", "Instance of 3 No");
        }
        transaction.replace(R.id.frag, frag3, "third");

        transaction.commit();
        }

    else if (pos == 4) {
        Fragment f = getSupportFragmentManager().findFragmentByTag("four");
        transaction = getSupportFragmentManager().beginTransaction();
        if (f instanceof Frag3) {
            frag4 = (Frag4) f;
            Log.i("MainAct", "Instance of 4 yes");
        }else{
            frag4 = Frag4.newInstance();
            Log.i("MainAct", "Instance of 4 No");
        }
        transaction.replace(R.id.frag, frag4, "four");
        transaction.commit();
    }

    }

}`

You are trying to call popBackStackImmediate("second", 0); 您正在尝试调用popBackStackImmediate("second", 0); instead replace the fragment. 而是替换片段。

Try this, 尝试这个,

  1. Create Interface PageTraveller and implement in MainActivity 创建Interface PageTraveller并在MainActivity中实现

     public interface PageTraveller { public void openPage(int pageNo); } 
  2. override the method openPage() 覆盖方法openPage()

      @Override public void openPage(int pageNo) { android.support.v4.app.Fragment fragment; switch (pageNo){ case 1: fragment = getSupportFragmentManager().findFragmentByTag("fragmentOne"); fragmentManager.beginTransaction().replace(R.id.pageContainer,fragment).addToBackStack("fragmentOne").commit(); break; case 2: fragment = getSupportFragmentManager().findFragmentByTag("fragmentTwo"); if (fragment instanceof FragmentTwo) fragmentTwo = (FragmentTwo)fragment; else fragmentTwo = new FragmentTwo(); fragmentManager.beginTransaction().replace(R.id.pageContainer,fragmentTwo).addToBackStack("fragmentTwo").commit(); break; case 3: fragment = getSupportFragmentManager().findFragmentByTag("fragmentThree"); if (fragment instanceof FragmentTwo) fragmentThree = (FragmentThree)fragment; else fragmentThree = new FragmentThree(); fragmentManager.beginTransaction().replace(R.id.pageContainer,fragmentThree).addToBackStack("fragmentThree").commit(); break; case 4: fragment = getSupportFragmentManager().findFragmentByTag("fragmentFour"); if (fragment instanceof FragmentTwo) fragmentFour = (FragmentFour)fragment; else fragmentFour = new FragmentFour(); fragmentManager.beginTransaction().replace(R.id.pageContainer,fragmentFour).addToBackStack("fragmentFour").commit(); break; } } 
    1. Create First fragment FragmentOne 创建第一个片段FragmentOne

      public class FragmentOne extends Fragment{ PageTraveller pageTraveller; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View viewOne = inflater.inflate(R.layout.fragment_one,null); Button btnOne = (Button)viewOne.findViewById(R.id.text1); btnOne.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pageTraveller.openPage(2); } }); return viewOne; } @Override public void onAttach(Context context) { super.onAttach(context); pageTraveller = (PageTraveller) context; } }

    in XML fragment_one add 在XMLfragment_one中添加

     <Button android:id="@+id/btnOne" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="40dp" android:layout_gravity="center|center_horizontal|center_vertical" android:text="Fragment 1"/> 

    1. Create FragmentTwo, FragmentThree, FragmentFour same way as above. 与上面相同的方式创建FragmentTwo,FragmentThree,FragmentFour。 but in your FragmentFour call pageTraveller.openPage(2); 但在您的FragmentFour调用pageTraveller.openPage(2);

For more reference try 1. go back to the previous fragment in the backstack 有关更多参考,请尝试1. 返回Backstack中的上一个片段

  1. Fragments official Android Developer website Fragments官方Android开发人员网站

Its work for me, try it may help you. 它对我有用,请尝试它可能对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM