我有一個ImageButton,我想在我的應用程序的某個Fragment類中使用它。但是當我在片段類中使用它時,應用程序崩潰。但我可以在我的MainActivity中使用它而不會崩潰。我怎樣才能解決這個問題?onClick方法只適用於MainActivity
這是我使用我的片段類代碼
public void showPopup(View v) {
PopupMenu popup = new PopupMenu(activity, v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.song_popup, popup.getMenu());
popup.show();
}
這導致應用crash.But當我使用這在我的MainActivity(在mainactivity「活動」是由this.getApplicationContext取代) 有用。
我的按鈕XML
<ImageButton
android:id="@+id/popUp"
android:layout_width="20dp"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_marginRight="2dp"
android:background="@null"
android:src="@drawable/abc_ic_menu_moreoverflow_mtrl_alpha"
android:onClick="showPopup" />
logcat的
java.lang.IllegalStateException: Could not find a method showPopup(View) in the activity class com.fm.etunes.phone.MainActivity for onClick handler on view class android.widget.ImageButton with id 'popUp'
at android.view.View$1.onClick(View.java:3814)
at android.view.View.performClick(View.java:4442)
at android.view.View$PerformClick.run(View.java:18473)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NoSuchMethodException: showPopup [class android.view.View]
at java.lang.Class.getConstructorOrMethod(Class.java:472)
at java.lang.Class.getMethod(Class.java:857)
at android.view.View$1.onClick(View.java:3807)
at android.view.View.performClick(View.java:4442)
at android.view.View$PerformClick.run(View.java:18473)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606)
at dalvik.system.NativeStart.main(Native Method)
檢查這一點 - http://stackoverflow.com/a/21192511/1479511 – NarendraJi
檢查答案http://stackoverflow.com/a/7808223/1168654解決方案是http://stackoverflow.com/a/6271637/1168654 –