Android - 片段到活动和返回

时间:2014-06-27 03:22:44

标签: android android-fragments

在Android中,当我们用新片段替换容器视图时,我们可以使用replace()和addToBackStack(),所以在按下后退按钮时我们转到上一个片段。

但如果发生以下情况该怎么办:

Activity1(fragment1 - > fragment2 [调用Activity2的startActivity]) - >活性2

在Activity1中,我可以按回按钮从fragment2转到fragment1。但是当fragment2启动另一个活动时,在按下Activity2的后退按钮时,它会将我带到Activity1中的fragment1。如何从Activity2返回按钮返回到Activity1中的fragment2?

代码:

// In Activity1 - starts with a ListFragment
@Override
protected void onResume() {
    super.onResume();

    getFragmentManager().beginTransaction()
            .replace(R.id.container, ListFragment.newInstance(0))
            .commit();
}

// In Activity1 , each item in list replaces the container view 
// with new fragment
@Override
public void onItemSelected(int position) {

    if(position == 0) {

        getFragmentManager().beginTransaction()
                .replace(R.id.container, Example1_Fragment.newInstance(0))
                .addToBackStack(null)
                .commit();

    }
   ....
 }

 // In Example1_Fragment

public class Example1_Fragment extends Fragment {

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.example1_fragment, container, false);

    Button btnIntent = (Button) view.findViewById(R.id.btnIntent);
    btnIntent.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent();
            intent.setAction("com.android.test2.app.example1_action");
            startActivityForResult(intent,1);
        }
    });

    return view;
}

// this is why I want to come back to Example1_Fragment - 
// the activity I start has to send a result back to
// the Example1_Fragment, but on back button, it takes me
// back to the ListFragment, and I cannot take any UI
// action (change to UI) in Example1_Fragment, as the
// ListFragment gets displayed - the onActivityResult of
// Example1_Fragment does get called

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == 1 && resultCode == Activity.RESULT_OK){

             // do something
    }
}

2 个答案:

答案 0 :(得分:2)

不要在onResume()回调中替换Fragment1,当你回到activity1时总是会调用这个方法,请在onCreate()回调中执行。

答案 1 :(得分:-1)

您可以在第二个活动中手动设置此方法内的后退调用。因此,当您按下时,您可以通过其标记找到片段2并将其添加回来。

@Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
            Intent i = new Intent(this, firstActivity.class);
            startActivity(i);
            FragmentTwo fragmentTwo = manager.findFragmentByTag("fragmentTwoTag");
            manager.beginTransaction.replace(fragmentOne, fragmentTwo).addToBackStack(null).commit();


    }