问题描述
我正在使用.xml视图的onClick方法来捕获.java类上的点击事件.
I am using onClick method of .xml view to catch the click events on my .java class.
通常运行良好.但是,当我的Activity在后台长时间运行时,稍后进入主线程并有人单击该视图,它将返回以下异常:
Usually runs fine. But when my Activity is running on background for a long time, later come to main thread and somebody clicks the view it returns the following exception:
java.lang.NullPointerException
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3608)
at android.view.View.performClick(View.java:4101)
at android.view.View$PerformClick.run(View.java:17087)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
这是我的view.xml:
Here my view.xml:
<ToggleButton
android:id="@+id/fragment_main_colonies_tbFollow"
android:layout_width="match_parent"
android:layout_height="40dp"
android:checked="false"
android:onClick="onClickToggleColonyFollow"
android:textOff="@string/main_colony_follow"
android:textOn="@string/main_colony_follow" />
这是我的fragment.java:
And here is my fragment.java:
public void onClickToggleColonyFollow(View view) {
ToggleButton near = (ToggleButton)getView().findViewById(R.id.fragment_main_colonies_tbNear);
ToggleButton follow = (ToggleButton) view;
if(follow == null || near == null) return;
if(!near.isChecked() && !follow.isChecked()) {
follow.setChecked(true);
return;
}
near.setChecked(false);
showColoniesNear = false;
}
我做错了什么?
推荐答案
使用android:onClick
属性时,它将尝试通过反射查找方法.我不清楚它到底在哪里尝试执行此操作,但它似乎一直都无法正常工作,也许它只是在视图附加到的Activity中寻找方法.我总是喜欢自己用view.setOnClickListener()
When you use the android:onClick
attribute, it tries to find the method via reflection. It's not clear to me exactly where it tries to do this, but it seems to not work all the time, perhaps it only looks for the method in the Activity the view is attached to. I always prefer to explicitly set the onClickListener myself with view.setOnClickListener()
这篇关于android:onClick =“"“导致IllegalStateException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!