java设置onclicklistener抛出异常?

cotxawn7  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(319)

我想知道为什么我的应用程序在运行时抛出运行时异常?我习惯于在我的应用程序的以下链接中使用代码,动态地将视图添加到viewpager并将其删除。

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

    ActionBar ab=getActionBar();

    pagerAdapter = new MainPagerAdapter();
    pager = (ViewPager) findViewById (R.id.pager);

    pager.setAdapter (pagerAdapter);

    inflater = (LayoutInflater)getSystemService
              (Context.LAYOUT_INFLATER_SERVICE);
    v0 = (FrameLayout) inflater.inflate (R.layout.listlayout, null);
    Button button=(Button)findViewById(R.id.button1);
    button.setOnClickListener(this);

    pagerAdapter.addView (v0, 0);

    pagerAdapter.notifyDataSetChanged();

}
@Override
public void onClick(View v) {
    if(v.getId()==R.id.button1)
    {
        pagerAdapter.addView (v0);

        pagerAdapter.notifyDataSetChanged();
    }

}

日志:

FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.todolistworkable/com.example.todolistworkable.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
at android.app.ActivityThread.access$600(ActivityThread.java:128)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4514)
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:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)Caused by: java.lang.NullPointerException
at com.example.todolistworkable.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)
kzipqqlq

kzipqqlq1#

oncreate方法中代码第43行的对象为空。很可能你的findviewbyid调用的目标没有返回你期望的结果。
有关详细信息,请参阅此。如何解释logcat

相关问题