我有一个包含自定义单元格的GridView(单元格包含TextView
,ImageView
和Button
)。这是GridView的自定义Adapter
类:
public class CustomGridViewAdapter extends ArrayAdapter<Item> {
Context context;
int layoutResourceId;
int test;
ArrayList<Item> data = new ArrayList<Item>();
public CustomGridViewAdapter(Context context, int layoutResourceId,
ArrayList<Item> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
RecordHolder holder = null;
test = position;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RecordHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.item_text);
holder.imageItem = (ImageView) row.findViewById(R.id.item_image);
holder.action = (Button) row.findViewById(R.id.item_action);
row.setTag(holder);
} else {
holder = (RecordHolder) row.getTag();
}
Item item = data.get(position);
holder.txtTitle.setText(item.getTitle());
Picasso.with(getContext()).load(item.getImageUrl()).into(holder.imageItem);
holder.action.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getContext(), "Posizione: "+ position, Toast.LENGTH_LONG).show();
}
});
return row;
}
static class RecordHolder {
TextView txtTitle;
ImageView imageItem;
Button action;
}
}
我从我的活动传递的数组中获取文本和图像,现在我想为每个按钮添加一个特定的操作,但我无法理解如何操作。 例如,如果我想通过单击按钮调用Activity中的方法,我该怎么办?
修改
我将位置声明为Final
以及当我点击按钮Toast
显示正确的位置时,现在我需要知道如何在点击按钮时从我的MainActivity调用方法
答案 0 :(得分:0)
不确定Android生命周期如何影响直接Java约定,但如果为每个按钮注册一个OnClickListener的新实例,则将根据推送的当前按钮发出每个方法调用。如果您关心方法调用和参数,可以扩展OnClickListener。这样的事情可能是:
private class MyListener extends View.OnClickListener {
param1, param2, paramN...;
public MyListener(arg1, arg2, argN...) {
//set vars
}
@Override
public void onClicked(ClickEvent theEvent) {
//do work with your unique parameters for that listener
//Call back to a method contained within your class as you wanted.
}
}