Java Android:如何访问活动类中的非活动Xml onClick属性方法
我有一个Java Android:如何访问活动类中的非活动Xml onClick属性方法,java,android,customdialog,Java,Android,Customdialog,我有一个CustomDialog,在上面我使用了数百个textview和onClick属性,现在我想在活动类中访问这些onClick方法。由于此CustomDialog是从Activity类中膨胀出来的,我想在该类上访问onClick方法,因此当我为该onClick创建方法时 public void playerEdit(View view) { Toast.makeText(this,"hello",Toast.LENGTH_LONG).show(); } 显然,它抛出了一个
CustomDialog
,在上面我使用了数百个textview
和onClick
属性,现在我想在活动类中访问这些onClick
方法。由于此CustomDialog
是从Activity
类中膨胀出来的,我想在该类上访问onClick
方法,因此当我为该onClick
创建方法时
public void playerEdit(View view) {
Toast.makeText(this,"hello",Toast.LENGTH_LONG).show();
}
显然,它抛出了一个异常
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'
这意味着我试图在一个不可访问的类中获取它
我的问题是如何在活动类中访问它
如何处理此异常
?
非常感谢您提前…您的xml文件可能有一个输入错误。方法名是“playeEdit”,而不是“playeEdit”我确信,当您构建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);
如前所述,您将向生成器传递您的类,如下所示:
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);
这确实有效。。。我测试过了 这里写错了,我在xml和课堂上都有PlayeEdit,