android:onClick=“” causes IllegalStateException

折月煮酒 提交于 2019-12-08 08:10:39

问题


I am using onClick method of .xml view to catch the click events on my .java class.

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)

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" />

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;
}

What I doing wrong?


回答1:


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()



来源:https://stackoverflow.com/questions/23426999/androidonclick-causes-illegalstateexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!