gpt4 book ai didi

java - PerformClick()方法返回错误

转载 作者:行者123 更新时间:2023-12-01 16:40:55 28 4
gpt4 key购买 nike

我有 2 个类被 fragment 覆盖。主页.javahometwo.java

单击名为 home.java 的类的名为 btn 的按钮。我希望在名为 btnctwo 的按钮上自动单击名为 hometwo.java 的类。

home.java

public class home extends Fragment {
Button btn;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home, container, false);



btn = rootView.findViewById(R.id.btnc);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hometwo hometwox = new hometwo();

hometwox.btnctwo
.post(new Runnable(){
@Override
public void run() {
hometwox.btnctwo.performClick();

}
});
}
});

return rootView;



}
}

hometwo.java

public class hometwo extends Fragment {
Button btnctwo;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home, container, false);



btnctwo = rootView.findViewById(R.id.btnctwo);






btnctwo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("testler","testlertwo");

}
});

return rootView;



}



}

日志猫

2020-05-18 11:17:54.907 11290-11290/com.sahnartsappone.sahnartsapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sahnartsappone.sahnartsapp, PID: 11290
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.Button.post(java.lang.Runnable)' on a null object reference
at com.sahnartsappone.sahnartsapp.home$1.onClick(home.java:30)
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)

为什么performClick()方法不起作用?我哪里出错了?

最佳答案

问题出在这里:

hometwo hometwox = new hometwo();

hometwox.btnctwo
.post...

如果您只创建 fragment ,它将无法到达 onCreateView 方法,因此它不会从 hometwox 注入(inject) btnctwo 按钮 View 中的按钮实例(因为不会有任何 View )。因此基本上您将在空引用上调用 post 方法。

因此解决方案是使用如下方式渲染 fragment :

 FragmentTransaction transaction = this.fragmentManager.beginTransaction();
transaction.replace(R.id.frame_container, fragment);
transaction.addToBackStack(null);
transaction.commit();

关于java - PerformClick()方法返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61865570/

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