簡體   English   中英

ActionBar中的Home Up按鈕不起作用

[英]Home Up Button in ActionBar doesn't work

我在ActionBar的Home Up按鈕有問題。 我在PreferenceActivity ,在onCreate我輸入了以下代碼:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }

當我運行我的應用程序時,它顯示了向上按鈕,但是當我單擊它時什么也沒有發生。 所以我把這段代碼放在AndroidManifest

    <activity android:name="com.example.mypackage.SystemInfo">
      <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.simonedev.androtools.MainActivity" />
    </activity>

但是我仍然有同樣的問題。 我該如何解決? 問題出在哪兒?

錯誤的方式

你不應該使用

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);
    switch(item.getItemId()) {
        case android.R.id.home:
        //Do not use the following
        //PreferenceActivity.this.onBackPressed(); 
        //or
        //finish();
        break;
    }
    return true;   
}

正確的方法

但是,請遵循此演示文稿Google准則

清單應再添加1個屬性

<activity android:name="com.example.mypackage.SystemInfo"
    android:parentActivityName="com.simonedev.androtools.MainActivity" >
  <meta-data
    android:name="android.support.PARENT_ACTIVITY"
    android:value="com.simonedev.androtools.MainActivity" />
</activity>

演示文稿中復制的代碼:這將是簡單的情況

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

我邀請您閱讀整個演示文稿,以了解其他更復雜的情況

在您的課程中添加此方法,但在onCreate()方法之外

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.action_bar, menu);
setTitle("");
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
 super.onOptionsItemSelected(item);
 switch(item.getItemId())
 {

case android.R.id.home:
PreferenceActivity.this.onBackPressed(); 
break;


 }
 return true;   
 }

現在,在您發表評論之后。 您可能需要在res / menu文件夾中創建一個名為action_bar.xml文件,並將以下內容添加到其中

 <menu xmlns:android="http://schemas.android.com/apk/res/android">
 </menu>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM