简体   繁体   English

从另一个 Activity 返回后返回到 MainActivity 的片段?

[英]Returning to MainActivity's fragment after return back from another Activity?

I have two Activities: MainActivity and OtherActivity .我有两个活动: MainActivityOtherActivity A fragment in MainActivity launches the OtherActivity , but when I press the back button at the top, it returns me to the MainActivity instead of the fragment that launched the OtherActivity . MainActivity中的一个片段启动了OtherActivity ,但是当我按下顶部的后退按钮时,它返回到MainActivity而不是启动OtherActivity的片段。

The end result is the enduser is sent back to the main screen instead of the fragment that they were using.最终结果是最终用户被送回主屏幕,而不是他们正在使用的片段。

This is my manifest .这是我的清单 I have set MainActivity to be the parent of OtherActivity :我已将MainActivity设置为OtherActivity的父级:

    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".OtherActivity"
        android:parentActivityName="com.example.test.MainActivity" >
    </activity>

In MainActivity , when a user clicks on a button, it loads a List fragment:MainActivity中,当用户单击按钮时,它会加载一个 List 片段:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // ...

    button.findViewById(R.id.events).setOnClickListener(new View.OnClickListener() {

         Fragment ef = new MyItemsFragment();
         FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
         fragmentTransaction.addToBackStack(null);
         fragmentTransaction.replace(R.id.content, ef, "my_fragment");
         fragmentTransaction.commit();
     });

}

public void callOtherActivity() {
    Intent i = new Intent(this, OtherActivity.class);
    this.startActivity(i);
}

When an item is clicked in the List Fragment, it launches OtherActivity.单击列表片段中的项目时,它会启动 OtherActivity。 A lot of the code for this was auto-generated by android studio.很多代码都是由 android studio 自动生成的。 I have changed some of it.我已经改变了一些。 In MyItemsRecyclerViewAdapter :MyItemsRecyclerViewAdapter 中

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
    holder.mItem = mValues.get(position);

    holder.mView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (null != mListener) {
                // Notify the active callbacks interface (the activity, if the
                // fragment is attached to one) that an item has been selected.
                mListener.onEventFragmentInteraction(holder.mItem);

                MainActivity ma = (MainActivity) holder.mView.getContext();
                ma.callOtherActivity();

            }
        }
    });
}

Notice it calls ma.callOtherActivity() , which is defined in MainActivity and will launch OtherActivity when an item is clicked in the list fragment.请注意,它调用ma.callOtherActivity() ,它在 MainActivity 中定义,并会在单击列表片段中的项目时启动 OtherActivity。

This is OtherActivity :这是其他活动

public class OtherActivity extends AppCompatActivity {

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

}

Now, when I click on the back arrow button in OtherActivity , the app will just show MainActivity , and not the List fragment that the user last saw.现在,当我单击OtherActivity中的后退箭头按钮时,应用程序将只显示MainActivity ,而不是用户最后看到的 List 片段。

How can I make sure that on return from OtherActivity, the user will see the list fragment again for better user experience?如何确保从 OtherActivity 返回时,用户将再次看到列表片段以获得更好的用户体验?

EDIT: There seems to be confusion about the 'back' button.编辑:似乎对“后退”按钮感到困惑。 Maybe they are the same, but I am talking about the one when switching Activities.也许它们是相同的,但我说的是切换 Activity 时的那个。 It is not the back button used to exit the application.它不是用于退出应用程序的后退按钮。 See image见图片

When you start a new activity, the existing one is stacked so you can retrieve it later such as when you press the Back key.当您开始一项新活动时,现有活动会堆叠起来,以便您稍后可以检索它,例如当您按返回键时。

On pressing the Back key, the Activity is restarted.按返回键后,活动将重新启动。 This is the important part.这是重要的部分。 It is not just brought back exactly as it was when it was last used.它不仅恢复到上次使用时的原样。 This means that you as the developer must take care to restore the Activity back to the state that you want it to be in. Any fragments will already be in the correct state but you must take care to not overwrite that state when your Activity restarts.这意味着您作为开发人员必须注意将 Activity 恢复到您希望它所处的状态。任何片段都将处于正确的状态,但您必须注意不要在 Activity 重新启动时覆盖该状态。

In your case, I suspect that your MainActivity code is indiscriminately re-initialising your fragments instead of checking whether fragments already exist for that particular activity before conditionally initialising them only if they don't.在你的情况下,我怀疑你的 MainActivity 代码不加区别地重新初始化你的片段,而不是检查片段是否已经存在于该特定活动之前,只有在它们不存在时才有条件地初始化它们。

It is difficult to say for sure as you do not include any of that code in your question.很难肯定地说,因为您没有在问题中包含任何该代码。 Check the code that displays the fragments in your MainActivity.检查在 MainActivity 中显示片段的代码。 Before you display them, are you checking whether there are already fragments visible?在显示它们之前,您是否检查是否已经有可见的片段? If not, you should be.如果不是,你应该是。

For example, the code below in an Activity, first checks whether a fragment is already displayed before it adds a new one.例如,下面的代码在 Activity 中,首先检查片段是否已经显示,然后再添加新片段。 Essentially, the first time this is run, there will be no Fragments and therefore existing will be null and a new Fragment will be created and displayed.本质上,这是第一次运行时,不会有片段,因此existing将为空,并且将创建并显示一个新的片段。

After you have started a new OtherActivity etc and then returned to this activity with the Back key, existing will no longer be null as the Fragment system will have restored any existing fragments back into your container.在您开始一个新的OtherActivity等然后使用返回键返回到此活动之后, existing将不再为空,因为片段系统会将任何现有的片段恢复到您的容器中。 Therefore we actually just do nothing.因此我们实际上什么都不做。

@Override
protected void onCreate(Bundle b) {
    super.onCreate(b);

    Fragment existing = getSupportFragmentManager().findFragmentById(R.id.content);

    if (existing == null) {
        Fragment newFragment = new MyFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content, newFragment)
                .commit();
    }

}

Hope this is clear.希望这是清楚的。

Just delete this line fragmentTransaction.addToBackStack(null);只需删除这一行fragmentTransaction.addToBackStack(null);

you can use getSupportFragmentManager().getBackStackEntryCount();你可以使用 getSupportFragmentManager().getBackStackEntryCount(); method in MainActivity's onBackPressed Method. MainActivity 的 onBackPressed 方法中的方法。 OnClick bottom System back button. OnClick 底部系统后退按钮。 follow below method.按照下面的方法。

@Override
public void onBackPressed() {    
int backstack = getSupportFragmentManager().getBackStackEntryCount();
 if (backstack > 0) {
        getSupportFragmentManager().popBackStack();
    } else {
            super.onBackPressed();
            System.exit(0);
      }}

In fragment, press the back button at the top.在片段中,按顶部的后退按钮。 try this, in onCreate method or onCreateView method of Fragment call this default method试试这个,在 Fragment 的 onCreate 方法或 onCreateView 方法中调用这个默认方法

setHasOptionsMenu(true);

and then override below method:然后覆盖下面的方法:

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
             getFragmentManager().popBackStack();
             break;
         }
       return super.onOptionsItemSelected(item);
}

You can use Activity for result for this start Other Activity and as soon as you want to finish OtherActivity just do setResult, MainActivity would receive this result and there do the following您可以将 Activity 用于此启动其他 Activity 的结果,一旦您想完成 OtherActivity 只需执行 setResult,MainActivity 将收到此结果并执行以下操作

if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
        getSupportFragmentManager().popBackStack();
    }

The code would go like this in MainActivity代码在 MainActivity 中会像这样

public void callOtherActivity() {
    Intent i = new Intent(this, OtherActivity.class);
   startActivityForResult(i, 1);
}

and in OtherActivity's onBackPress call below method.并在 OtherActivity 的 onBackPress 调用下面的方法。

Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();

and now in MainActivity onActivityresult现在在 MainActivity onActivityresult

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
            getSupportFragmentManager().popBackStack();
        }
    }
 }

I might be late but in my case error was coming because of the LoadFragment Method in OnStart method of MainActivity我可能会迟到,但在我的情况下,错误是由于 MainActivity 的 OnStart 方法中的 LoadFragment 方法

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

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