Android:导航返回使用与工具栏相同的活动

问题描述 投票:0回答:1

我有一个activity与不同的layouts。每次我想从一个布局转到另一个布局时,我都会使用Visibility属性。但我有一个toolbar,我不知道如何设置导航,因为我总是相同的活动。

在更多活动的正常情况下,我会使用属性android:parentActivityName,但在这种情况下我不能因为是相同的活动。

我的部分代码:

 <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">

<!-- SIGN-IN SCREEN -->
<LinearLayout android:id="@+id/screen_sign_in" style="@style/LLScreen">
    <TextView style="@style/GameTitle" />
    <TextView style="@style/GameBlurb" />

    <com.google.android.gms.common.SignInButton android:id="@+id/button_sign_in"
        style="@style/SignInButton" />
</LinearLayout>

<!-- MAIN SCREEN -->
(...)

我用来更改屏幕的可见性代码:

void switchToScreen(int screenId) {
        // make the requested screen visible; hide all others.
        for (int id : SCREENS) {
            findViewById(id).setVisibility(screenId == id ? View.VISIBLE : View.GONE);
        }

我该如何解决这个问题?

android android-toolbar
1个回答
2
投票

你的主要问题是你展示“屏幕”的方法是非常规的。与使用活动或片段的常规方法不同,您只需切换视图可见性,这些可见性没有任何内置历史记录显示的内容。

因此,这种方法的唯一解决方案是构建自己的缓存,显示已显示的内容。

这可以通过任何数据类型轻松完成,例如List。对于这个答案,我将以List为例。

首先,创建一个List实例来存储Activity中屏幕的历史记录:

List<Integer> listOfScreens = new ArrayList<Integer>();

接下来,确保在切换屏幕时添加到此列表:

listOfScreens.add(screenId);
switchToScreen(screenId);

这样,您将新屏幕添加到列表中,然后切换到正确的屏幕。

最后,在您的Navigation Up和onBackPressed()代码中,只需删除列表中的最后一个屏幕并再次切换。

@Override
public void onBackPressed() {
    listOfScreens.remove(listOfScreens.size()-1);
    switchToScreen(listOfScreens.get(listOfScreens.size()-1));
}

您将删除列表中当前屏幕的最后一项,然后将可见性切换回上一屏幕。

我已经在onBackPressed()方法中显示了执行此操作的代码,因此在ToolBar中对您的向上导航执行相同的操作。

© www.soinside.com 2019 - 2024. All rights reserved.