[英]Android: How to Access a non-Activity Xml onClick attribute method in an Activity Class
我有一個CustomDialog
在其中使用了數百個具有onClick
屬性的TextViews
,現在我想在Activity class
訪問這些onClick
方法。 由於此CustomDialog
是我要訪問onClick
方法的Activity
類的膨脹,所以當我為該onClick
創建方法時,就像
public void playerEdit(View view) {
Toast.makeText(this,"hello",Toast.LENGTH_LONG).show();
}
顯然,它引發了一個Exception
Could not find a method playeEdit(View) in the activity class android.view.ContextThemeWrapper for onClick handler on view class android.widget.TextView with id 'p1'
這意味着我試圖在不可訪問的類中獲取它,
我的問題是如何在該Activity Class
訪問它?
如何處理此Exception
? 在此先感謝...
您的xml文件中可能有錯字。 方法名稱是“ playeEdit”而不是“ playerEdit”
我確實相信,在構造AlertDialog時,您將以類似的方式進行操作:
ContextThemeWrapper themedContext = new ContextThemeWrapper(getActivity(),android.R.style.Theme_Dialog);
AlertDialog.Builder builder = new AlertDialog.Builder(themedContext);
(發布整個代碼有幫助)
您之所以會得到例外,是因為xml中的onClick處理程序在其中查找的活動(以及xml膨脹到的位置)是在該主題活動中,而不是原始活動!
您將需要擴展ContextThemeWrapper類,將其傳遞到構建器中,並實現您的點擊處理程序,如下所示:
public static class MyContextThemeWrapper extends ContextThemeWrapper
{
public MyContextThemeWrapper() {
super();
}
public MyContextThemeWrapper(Context base, int themeres) {
super(base, themeres);
}
public void playerEdit(View view)
{
// Do stuff when clicked
}
}
如前所述,您將像這樣將類傳遞給構建器:
MyContextThemeWrapper themedContext = new MyContextThemeWrapper(getActivity(), android.R.style.Theme_Dialog);
AlertDialog.Builder builder = new AlertDialog.Builder(themedContext);
確實有效...我測試了!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.