点击事件从一个标签移动到另一个标签

时间:2018-01-12 08:03:23

标签: java android

我创建了一个带有5个标签的应用,在我的第一个标签中,我点击了一个按钮,我想去tab3。这是我的按钮事件代码 -

moreButton3.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(view.getContext(), Tab3_Image.class);
        view.getContext().startActivity(intent);
    }
});

但是点击按钮时应用程序崩溃,下面是logcat错误 -

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.s2s.doupnow, PID: 22481
java.lang.NullPointerException
    at com.s2s.doupnow.Tab1_Home$6.onClick(Tab1_Home.java:313)
    at android.view.View.performClick(View.java:4444)
    at android.view.View$PerformClick.run(View.java:18457)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5113)
    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:796)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
    at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

改变这一点 - :

moreButton3.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(view.getContext(), Tab3_Image.class);
                view.getContext().startActivity(intent);
            }
        });

要 - :

private Context context=this;   //make it global

Button moreButton3=(Button)findViewById(R.id.buttoninxml);
moreButton3.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, Tab3_Image.class);
                startActivity(intent);
            }
        });