我有一个带有ListView的Android应用程序,ListView将设置正常,但现在我希望ListView中的图像可以点击。我通过使用2个类,Activity类(父)和ArrayAdapter来填充列表。在ArrayAdapter中,我为列表中我想要点击的图像实现了一个OnClickListener。
到目前为止一切正常。
但是现在我想在活动类中运行一个函数,当onClick(对于列表中的图像)运行但我不知道如何。以下是我使用的两个类。
首先是Activity类:
public class parent_class extends Activity implements OnClickListener, OnItemClickListener
{
child_class_list myList;
ListView myListView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// setup the Homelist data
myList = new child_class_list (this, Group_Names, Group_Dates);
myListView = (ListView) findViewById(R.id.list);
// set the HomeList
myListView.setAdapter( myList );
myListView.setOnItemClickListener(this);
}
void function_to_run()
{
// I want to run this function from the LiscView Onclick
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
// do something
}
}
我希望从Activity类调用函数的ArrayAdapter:
public class child_class_list extends ArrayAdapter<String>
{
// private
private final Context context;
private String[] mName;
private String[] mDate;
public child_class_list (Context context, String[] Name, String[] Date)
{
super(context, R.layout.l_home, GroupName);
this.context = context;
this.mName = Name;
this.mDate = Date;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.l_home, parent, false);
ImageView selectable_image = (ImageView) rowView.findViewById(R.id.l_selectable_image);
selectable_image.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// I want to run the function_to_run() function from the parant class here
}
}
);
// get the textID's
TextView tvName = (TextView) rowView.findViewById(R.id.l_name);
TextView tvDate = (TextView) rowView.findViewById(R.id.l_date);
// set the text
tvName.setText (mName[position]);
tvDate.setText (mDate[position]);
return rowView;
}
}
如果有人知道如何在arrayadapter中运行活动类中的函数,或者如何在Activity类中设置onClickListener中的图像,我会大大提供帮助。
答案 0 :(得分:44)
内部onClick()
执行以下操作:
((ParentClass) context).functionToRun();
答案 1 :(得分:8)
为了清楚地扩展提供的答案
在BaseAdapter中,您可以通过调用this.getActivity();
来获取父类。如果您将此类型转换为实际的活动类,则可以根据下面的@AdilSoomro回答调用函数,这样您实际上就会得到类似这样的内容
public class MyAdapter extends BaseAdapter<Long> {
public MyAdapter(Activity activity,
TreeStateManager<Long> treeStateManager, int numberOfLevels) {
super(activity, treeStateManager, numberOfLevels);
}
@Override
public void handleItemClick(final View view, final Object id) {
((MyActivity) this.activity).someFunction();
}
}
然后在MyActivity中声明someFunction以执行您想要的操作
protected void someFunction(){
// Do something here
}