自定义操作栏上的 NullPointerException,android?

NullPointerException on custom action bar, android?

我想在操作栏上给自己充气。但是我得到空指针异常。

这是我的操作栏 XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/white"
android:weightSum="1">
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center"
    android:text="Choose"
    android:textColor="#000000"
    android:id="@+id/mytext"
    android:textSize="18sp"
    android:layout_weight="0.94" />
</LinearLayout>

这就是我给它充气的方式

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_choose);
    ActionBar bar = getActionBar();
    bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    bar.setCustomView(R.layout.action_layout);

logcat-

java.lang.RuntimeException: Unable to start activity  ComponentInfo{com.ceapp/com.ceapp.ChooseActivity}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2246)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2296)
        at android.app.ActivityThread.access0(ActivityThread.java:145)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1243)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5136)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:819)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at ceat.vfconnect.com.ceatapp.ChooseActivity.onCreate(ChooseActivity.java:26)
        at android.app.Activity.performCreate(Activity.java:5231)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2210)

第 26 行是

bar.setCustomView(R.layout.action_layout);

我的代码有什么问题?

我相信这是您可以使用的另一种解决方案。它在我的应用程序中运行。

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Android.support.v7.app.ActionBar actionBar =getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);            
    setContentView(R.layout.activity_main)

你可以试试这个。

mActionBar = getActionBar();
mActionBar.setDisplayShowHomeEnabled(true);
mActionBar.setDisplayShowTitleEnabled(true);
mActionBar.setCustomView(R.layout.layut_custom_action_bar);