簡體   English   中英

getSupportActionBar()。setDisplayHomeAsUpEnabled(true)給出NullPOinterException

[英]getSupportActionBar().setDisplayHomeAsUpEnabled(true) gives NullPOinterException

getSupportActionBar().setDisplayHomeAsUpEnabled(true)給出NullPOinterException ,之后我嘗試了各種組合

  1. 活動( AppComatActivity ),
  2. 主題( Theme.AppCompat.LightTheme.Holo.Light )和
  3. 向上按鈕API( getSupportActionBar()getActionBar()

我知道這個問題已經被問過很多次了,但是請相信我,他們的解決方案都不對我有用。

我的座右銘:

我只是想為我的兒童活動設置向上按鈕。

我設定的前提條件:

我在清單文件中為子活動設置了以下內容

            android:parentActivityName="com.example.sony.myfirstapplication.MainActivity">

        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.sony.myfirstapplication.MainActivity"
            />

並在我的孩子活動中遵循代碼

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_message);

    //receive message
    Intent intent = getIntent();
    TextView txt = (TextView) findViewById(R.id.text_msg_show);
    String msg = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
    txt.setText(msg);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true); //Gives NullPointerException
}

清單文件中的主題:

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

在Style.xml文件中聲明的樣式:-

<style name="AppTheme" parent="@style/Theme.AppCompat.Light">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

注意

我已經從AppCompatActivity繼承了Activity,而不是ActionBarActivity

您應該首先設置工具欄:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setSupportActionBar.setDisplayHomeAsUpEnabled(true);

既然您說它不會崩潰 ,那么只需在該行上方添加: @SuppressWarnings("null")

否則,添加以下內容:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

第一

暫無
暫無

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

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