android:onClick=“” causes IllegalStateException

2019-06-09 00:27发布

问题:

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