当我点击左上角时,如何让Android ActionBar转到Home?

use*_*544 2 android android-layout

我看到了插入符号,但是当我点击它时没有任何反应.我在哪里告诉它转到家里并设置哪个活动是家庭?

A--*_*--C 10

你需要这条线:

getActionBar().setDisplayHomeAsUpEnabled(true);
Run Code Online (Sandbox Code Playgroud)

把它放进去onCreate();

这将使其可点击.您需要处理click事件.这是通过覆盖来完成的onOptionsItemSelected()

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
                switch (item.getItemId()) {
                case android.R.id.home:
                 finish();
                default: 
                 return super.onOptionsItemSelected(item);      
                }
        }
Run Code Online (Sandbox Code Playgroud)

如果你想使用NavUtils(我在ADT插件制作活动时看到过它)你可以替换更改实现,如下所示:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
              NavUtils.navigateUpFromSameTask(this);
                    return true;
        default: 
                      return super.onOptionsItemSelected(item); 
        }
    }
Run Code Online (Sandbox Code Playgroud)

别忘了

import android.support.v4.app.NavUtils;
Run Code Online (Sandbox Code Playgroud)

此外,您可以将其添加到您的Activity节点:

    <activity
        android:name=".SomeActivity"
        android:label="@string/activity_label" >
         <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.mypackage.MainActivity" />
    </activity>
Run Code Online (Sandbox Code Playgroud)

NavUtils通常是更好的方法.有关更多信息,请参阅官方Android 指南.


eig*_*tx2 5

在您的onCreate您有:

getActionBar().setDisplayHomeAsUpEnabled(true);
Run Code Online (Sandbox Code Playgroud)

然后使用:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
}
Run Code Online (Sandbox Code Playgroud)