gpt4 book ai didi

java - PerformClick()方法不起作用,出现错误

转载 作者:行者123 更新时间:2023-12-01 16:42:23 27 4
gpt4 key购买 nike

我有2个java类

我想在单击 btn 时单击 btntwo。

当我单击名为 btn 的按钮时,我想自动单击名为 btn 的按钮 2。但我收到一个错误。

主要 Activity

 public class MainActivity extends AppCompatActivity {
Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Log.e("test","testone");
final Main2Activity main2Activity = new Main2Activity();

main2Activity.btntwo
.post(new Runnable(){
@Override
public void run() {
main2Activity.btntwo.performClick();

}
}); }
});
}
}

Main2Activity

public class Main2Activity extends AppCompatActivity {
Button btntwo;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
btntwo = findViewById(R.id.btntwo);

btntwo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("test","testtwo");

}
});

}
}

我收到错误

2020-05-16 17:06:35.238 8529-8529/com.qarocotwo.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.qarocotwo.myapplication, PID: 8529
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.Button.post(java.lang.Runnable)' on a null object reference
at com.qarocotwo.myapplication.MainActivity$1.onClick(MainActivity.java:25)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

为什么我会收到错误消息?我哪里做错了你能帮我一下吗?

最佳答案

您在错误的位置创建了 Main2Activity 类的对象。

public class MainActivity extends AppCompatActivity {
Button btn;
Main2Activity main2Activity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
main2Activity = new Main2Activity();

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Log.e("test","testone");

main2Activity.btntwo
.post(new Runnable(){
@Override
public void run() {
main2Activity.btntwo.performClick();

}
}); }
});
}
}

关于java - PerformClick()方法不起作用,出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61838369/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com