在 Dialog 子类中设置 onClickListener 时出现 ClassCastException
我对 Dialog 进行了子类化以显示弹出窗口。该对话框包含一个 ListView,因此我还有一个内部类(在对话框中),它是 BaseAdapter 的子类。
我正在尝试为列表中的文本设置 onClickListener,但是我不断在 setOnClickListener 处收到 ClassCastException(请参阅下面的代码)。
public class CustomDialog extends Dialog
{
MyAdapter adapter = null;
public CustomDialog(Context context)
{
super(context);
setContentView(R.layout.custom_popup);
ListView listView = (ListView) findViewById(android.R.id.list);
adapter = new MyAdapter(context);
listView.setAdapter(adapter);
}
public class MyAdapter extends BaseAdapter implements OnClickListener
{
@Override
public View getView(int arg0, View arg1, ViewGroup arg2)
{
....
TextView groupText = (TextView)v.findViewById(R.id.mytext);
mytext.setOnClickListener((android.view.View.OnClickListener) this); //crashes here
....
}
@Override
public void onClick(DialogInterface arg0, int arg1)
{
}
}
}
I have subclassed Dialog in order to display a popup. This dialog contains a ListView, and so I also have an inner class (in the Dialog) that subclasses BaseAdapter.
I am trying to set the onClickListener for text that is within my list, however I keep getting ClassCastException at setOnClickListener (see code below).
public class CustomDialog extends Dialog
{
MyAdapter adapter = null;
public CustomDialog(Context context)
{
super(context);
setContentView(R.layout.custom_popup);
ListView listView = (ListView) findViewById(android.R.id.list);
adapter = new MyAdapter(context);
listView.setAdapter(adapter);
}
public class MyAdapter extends BaseAdapter implements OnClickListener
{
@Override
public View getView(int arg0, View arg1, ViewGroup arg2)
{
....
TextView groupText = (TextView)v.findViewById(R.id.mytext);
mytext.setOnClickListener((android.view.View.OnClickListener) this); //crashes here
....
}
@Override
public void onClick(DialogInterface arg0, int arg1)
{
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这种情况下,您会弄乱两个具有相同名称但不同包的类......
View.OnClickListener
和DialogInterface.OnClickListener
。您的类中的侦听器是DialogInterface.OnClickListener
,但您需要一个View.OnClickListener
。将您的工具更改为使用 View.OnClickListener 即可解决您的问题。In this case, you're messing with two classes that have the same name but different package....
View.OnClickListener
andDialogInterface.OnClickListener
. The listener you have in your class is aDialogInterface.OnClickListener
but you're wanting aView.OnClickListener
. Change your implement to useView.OnClickListener
and that'll fix your problem.