Android ActionBar setCustomView NullPointer异常

时间:2015-04-17 05:16:11

标签: android nullpointerexception android-actionbar

我正在使用android API 15并且我正在尝试为ActionBar设置一个简单的CustomView,并且出于某种原因我得到了NullPointer异常这是我的活动,异常发生在 actionBar.setCustomView(R.layout。 localview_actionbar);

public class LocalView extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.local_view);
    ActionBar actionBar = getActionBar();
    actionBar.setCustomView(R.layout.localview_actionbar);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    //  getActionBar().setDisplayShowTitleEnabled(false);
    getMenuInflater().inflate(R.menu.local_view, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if(id== R.id.action_edit)
    {
        Toast.makeText(this,"Popup Edit box",Toast.LENGTH_SHORT).show();
        return true;
    }
    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

这是错误消息

     Caused by: java.lang.NullPointerException
        at com.exoler.LocalView.onCreate(LocalView.java:19)
        at android.app.Activity.performCreate(Activity.java:4465)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
          at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:1981)
        at android.app.ActivityThread.access$600(ActivityThread.java:123)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4424)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
        at dalvik.system.NativeStart.main(Native Method)

和简单的自定义View:localview_actionbar.xml是

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<EditText
android:id="@+id/searchfield"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Text" />
</LinearLayout>

正如您所看到的,它是一个简单的SearchField。哦,我还尝试删除 onCreateOptionsMenu onOptionsItemSelected 方法,仍然得到错误,任何建议都会很棒。我在这里搜索了答案,但没有找到答案。

1 个答案:

答案 0 :(得分:3)

更改

public class LocalView extends Activity

public class LocalView extends ActionBarActivity

也喜欢

ActionBar actionBar=getSupportActionBar();