在布局 xml 中使用 onClick 属性会导致 Android 对话框中出现 NoSuchMethodException [英] Using onClick attribute in layout xml causes a NoSuchMethodException in Android dialogs
本文介绍了在布局 xml 中使用 onClick 属性会导致 Android 对话框中出现 NoSuchMethodException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个自定义对话框和一个布局 xml:
I have created a custom dialog and a layout xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tap Me"
android:onClick="dialogClicked" />
</LinearLayout>
在对话框类中我实现了方法dialogClicked(View v)":
In the dialog class I've implemented the method "dialogClicked(View v)":
public class TestDialog extends Dialog {
public TestDialog(final Context context)
{
super(context);
}
@Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
}
public void dialogClicked(final View view)
{
System.out.println("clicked");
}
}
当我点击按钮时,我得到一个 NoSuchMethodException 'dialogClicked'.在布局 xml 中设置 onClick 处理程序适用于活动,但不适用于对话框.有任何想法吗?我做错了什么?
When I tap the button I get a NoSuchMethodException 'dialogClicked'. Setting the onClick handler in layout xml works fine for activities, but not in dialogs. Any ideas? What I'm doing wrong?
推荐答案
在Activity中定义方法(dialogClicked).并修改 TestDialog 如下代码:
Define the method (dialogClicked) in Activity. And modify TestDialog like the following code:
public class TestDialog extends Dialog {
Context mContext;
public TestDialog(final Context context)
{
super(context);
mContext=context;
}
@Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
LinearLayout ll=(LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.dialog, null);
setContentView(ll);
}
}
我认为它有效:)
这篇关于在布局 xml 中使用 onClick 属性会导致 Android 对话框中出现 NoSuchMethodException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文