【问题标题】:Handle Up navigation from Action Bar like Back navigation. How?处理来自操作栏的向上导航,如后退导航。如何?
【发布时间】:2015-02-24 20:23:37
【问题描述】:

如何处理像后退导航一样的向上导航?

是否有类似后退导航(onBackPressed())的向上导航方法?

或者当我按下向上导航时,我可以编写finish() 方法吗?

【问题讨论】:

  • 您需要展示您的代码示例以便我们为您提供帮助。

标签: java android navigation android-actionbar back


【解决方案1】:

假设“向上导航”是指点击应用图标,您需要在 Activity 中覆盖 onOptionsItemSelected() 并像这样处理它:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // 'home' is the id for the icon click in the action bar (i.e. up/back).
    if (item.getItemId() == android.R.id.home) {
        // do your thing and return true
        return true;
    }

    return super.onOptionsItemSelected(item);
}

【讨论】:

    【解决方案2】:

    有很多方法可以做到这一点:

    1. 使用 onOptionsItemSelected() 方法,如上面 nitzanj 的回答。
    2. 在您的Activity 中使用onBackPressed()finish() 方法就像您的问题一样(无效)。

    3. 使用setDisplayHomeAsUpEnabled()方法。


    setDisplayHomeAsUpEnabled()方法如何使用?

    首先,在您的onCreate 方法中,添加:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details);
    
        // use getActionBar() if API is higher than 11
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        ...
    }
    

    现在操作栏中的图标出现了带有向上插入符号(如图所示)。但是,默认情况下它不会做任何事情。要指定当用户按下向上按钮时要打开的活动,您有两种选择:

    1.在清单文件中指定父 Activity。

    父活动始终相同时,这是最佳选择。通过在清单中声明哪个活动是父活动,当用户按下向上按钮时,操作栏会自动执行正确的操作。 从 Android 4.1(API 级别 16)开始,您可以在 <activity> 元素中使用 parentActivityName 属性声明父级。 要使用支持库支持旧设备,还需要包含一个<meta-data> 元素,该元素将父活动指定为android.support.PARENT_ACTIVITY 的值。例如:

    <application ... >
        ...
        <!-- The main/home activity (it has no parent activity) -->
        <activity
            android:name="com.example.myfirstapp.MainActivity" ...>
            ...
        </activity>
        <!-- A child of the main activity -->
        <activity
            android:name="com.example.myfirstapp.DisplayMessageActivity"
            android:label="@string/title_activity_display_message"
            android:parentActivityName="com.example.myfirstapp.MainActivity" >
            <!-- Parent activity meta-data to support 4.0 and lower -->
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.myfirstapp.MainActivity" />
        </activity>
    </application>
    

    一旦像这样在清单中指定父 Activity 并使用 setDisplayHomeAsUpEnabled() 启用 Up 按钮,您的工作就完成了,操作栏正确地向上导航。

    2。或者,在您的活动中覆盖 getSupportParentActivityIntent()onCreateSupportNavigateUpTaskStack()

    父 Activity 可能因用户到达当前屏幕的方式而不同时,这是合适的。也就是说,如果用户可以通过许多路径到达当前屏幕,则向上按钮应该沿着用户实际到达那里的路径向后导航。 Read more

    来源:

    Providing Up Navigation

    Navigating Up with the App Icon

    【讨论】:

      猜你喜欢
      • 2017-06-25
      • 1970-01-01
      • 2020-12-17
      • 2018-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-03
      • 1970-01-01
      相关资源
      最近更新 更多