简体   繁体   English

是否真的需要编写Java代码来显示Android中的“向上导航”按钮?

[英]Is it really necessary to write Java code to display the Up Navigation Button in Android?

When I want to provide Up Navigation in the ActionBar of an Android activity, I just write these lines of code in the AndroidManifest.xml: 当我想在Android活动的ActionBar中提供向上导航时,只需在AndroidManifest.xml中编写以下代码行:

<activity android:name=".SettingsActivity"
    android:parentActivityName=".MainActivity">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value=".MainActivity"/>
</activity>

However, now I've just saw these lines of code in the java file: 但是,现在我刚刚在java文件中看到了以下代码行:

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

    ActionBar actionBar = this.getSupportActionBar();

    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int itemId = item.getItemId();
    switch (itemId) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
        default:
            return super.onOptionsItemSelected(item);
    }
}

All my previous projects just worked without the these lines of Java. 我以前的所有项目都在没有这些Java代码的情况下工作。 Are they really necessary? 他们真的有必要吗? If they are, are they necessary for compatibility for android versions? 如果是的话,是否有必要兼容Android版本? In this case, previous to which version? 在这种情况下,使用哪个版本?

You should be using Appcompat which is a compatibility library to access and customize different ui elements known as views on api 7<= . 您应该使用Appcompat ,它是一个兼容性库,用于访问和自定义不同的ui元素,称为api 7 <=上的视图。 When you override " onOptionsItemSelected ", you add a custom action to a button on the action bar (so now isnthe implementation of NavUtils.navigateUpFromSameTask(this) ). 当您覆盖“ onOptionsItemSelected ”时,会将自定义操作添加到操作栏上的按钮上(所以现在不是NavUtils.navigateUpFromSameTask(this)的实现 )。 So let your activity extend AppCompatActivity (if it isn't already). 因此,让您的活动扩展AppCompatActivity(如果尚未扩展)。

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

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