简体   繁体   English

Android-如何直接转到后退堆栈中的上一个活动,而忽略片段后退堆栈或当前活动中的剩余片段?

[英]Android - How to go directly to previous activity in back stack and ignore the fragment backstack or remaining fragments in current activity?

There are questions regarding back stack and fragmentManager but I didn't find any that have this similar use case. 关于后栈和fragmentManager存在一些问题,但没有找到具有类似用例的问题。

So Here is my use case: on a tablet, I have the main activity on the left that acts as a navigation page, and fragments showing on the right when users click on things on the left. 因此,这是我的用例:在平板电脑上,我的左侧主要活动是导航页,当用户单击左侧的内容时,右侧会显示片段。 Eg when clicking on General , the general page will be shown on the right. 例如,单击“ Generalgeneral页面将显示在右侧。 Let's say I navigate from Homepage to this Settings activity which has General and other settings, I show the General page on the right as default on the tablet (so that the right part won't be blank), and when I click on the back button, I want to go back directly to Homepage instead of showing the blank right part. 假设我从“ Homepage Settings导航到具有“ General和其他设置的Settings活动,我在平板电脑上默认情况下在右侧显示“ General页面(以使右侧部分不会为空白),然后单击背面按钮,我想直接返回Homepage而不是显示空白的右侧部分。 I fixed this by: 我通过以下方式解决了这个问题:

override fun onBackPressed() {
    //some code
    if (isTabletLayout && supportFragmentManager.backStackEntryCount == 1) {
        supportFragmentManager.popBackStack()
    }
    super.onBackPressed()
    //some other code
}

However, even if I do this, I will see the right part flashes to blank and then I was shown the previous activity (in the example, the Homepage ) 但是,即使执行此操作,我也会看到右侧的部分闪烁为空白,然后向我显示了上一个活动(在示例中为Homepage

Now I'm wondering if I can just ignore that last fragment or delete the fragment back stack when there is only one left and directly show the previous activity? 现在,我想知道是仅剩下一个片段并直接显示上一个活动时,是否可以忽略最后一个片段或删除片段返回堆栈?

Thanks in advance. 提前致谢。

@Override
public void onBackPressed() {
    finish();
}

Just call finish() on onBackPressed() method. 只需在onBackPressed()方法上调用finish()即可。

There's a way around by just calling finish(); 只需调用finish();

However you shouldn't use your main activity as a navigation Tab. 但是,您不应将主活动用作导航选项卡。 That's straight up bad UI and will lead to a bad UX. 这直接导致不良的UI,并会导致不良的UX。

Rearrange your UI now and avoid bigger problems in the future. 立即重新布置您的UI,避免将来遇到更大的问题。

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

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