调用BaseAdapter的Activity,为行中的每个项设置OnClick()

时间:2012-05-03 03:25:31

标签: android onclick alertdialog baseadapter

没有显示太多代码:

我有Activity“A”。此Activity通过ListView填充BaseAdapterBaseAdapter的{​​{1}}为每一行中的项目设置getView()

我想在点击行项目时在onClickListener()“A”中显示AlertDialog

1 个答案:

答案 0 :(得分:1)

我看不到你遇到问题的地方。如果您在BaseAdapter A中使用了Activity版本,那么您可以在OnCLickListener中调用getView中为BaseAdapter方法设置的Activityprivate void showADialog(int position) { new AlertDialog.Builder(this) .setMessage("The clicked row is " + position) .setPositiveButton("Ok?", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); } 1}})您在A BaseAdapter中创建的私有方法:

Activity

如果您的自定义ContextBaseAdapter A不在同一文件中,那么您可以使用传递给Context的{​​{1}}(如果代码为你的适配器是你上一个问题的适配器,如果没有,你应该在构造函数中传递它)。然后,您可以将showADialog()投射到您的活动,并调用上一个方法position。此外,当您设置监听器时,您应该将OnCLickListener作为标签传递,以便您可以在//... item.setTag(new Integer(position)); // or if you use a ViewHolder: holder.item bla..... item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Integer realPosition = (Integer) v.getTag(); // Here show the dialog using one of the methods above.You either: // showADialog(realPosition); // when the code for your custom BaseAdapter in in the same class as Activity A //((CallingAlertDialogBaseAdapter) context).showADialog(realPosition); // when the code for the custom BaseAdapter is in a separate file then Activity A //create directly an AlertDialog. For this you'll require a valid Context(from an Activity(getApplicationCOntext() will NOT work). //You have this context from the parameter that you pass in the constructor of your custom BaseAdapter(as you ussualy pass this in the Activity where you instantiate the adapter) } }); //... 中检索它(否则您可能会因为视图+监听器被回收而得到错误的位置):

{{1}}