简体   繁体   中英

how to resume multiple fragments in the last state

I'm a beginner in Android and I need help please :(

I have 3 fragments in the main activity and each of the fragments has 4 buttons. What i want to achieve is to keep the fragment's last state persistent while moving from any of fragment to another, with the help of backstack. How do I do it ? Thank you

public class FragmentTraining extends SherlockFragmentActivity implements OnClickListener {

    Button fragOneBtn;
    Button fragTwoBtn;
    Button fragThreeBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_stack);
        initialize();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.new_fragment1:
            addFragmentToStack("id_one");
            break;
        case R.id.new_fragment2:
            addFragmentToStack("id_two");
            break;
        case R.id.new_fragment3:
            addFragmentToStack("id_three");
            break;
        }
    }

    private void initialize() {
        fragOneBtn = (Button) findViewById(R.id.new_fragment1);
        fragTwoBtn = (Button) findViewById(R.id.new_fragment2);
        fragThreeBtn = (Button) findViewById(R.id.new_fragment3);

        fragOneBtn.setOnClickListener(this);
        fragTwoBtn.setOnClickListener(this);
        fragThreeBtn.setOnClickListener(this);
    }

    void addFragmentToStack(String tag) {
        Fragment newFragment = getFragmentManager().findFragmentByTag(tag);
        Log.d("debug", "newFragment: " + newFragment + " , tag: " + tag);
        if (newFragment == null) {
            newFragment = new FragmentInstances();
        }
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.fl_container, newFragment, tag);
        ft.commit();
    }

}

Try to code to its life cycle through its parent activity.

You will have the onPause, onResume, onStop, and onStart methods to work with.

There is quite a bit of logic behind this so here is a link to help you, sorry for no code snippet :P

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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