我有一个使用ViewHolder模式的自定义适配器的Listview ...它运行正常,但现在我在我的布局中为listview中的每一行添加了两个按钮。
单击按钮时,我想获取位置(获取数据),我实现了OnClickListener
我该怎么做?
这是我的代码的一部分:
public class SearchListAdapter extends BaseAdapter implements OnClickListener {
public static final String TAG = "SearchListAdapter";
private LayoutInflater inflater;
private ArrayList<VideoYoutube> arrayList;
private ImageLoader imageLoader;
private Activity activity;
public SearchListAdapter(Activity a, ArrayList<VideoYoutube> array){
activity = a;
arrayList = array;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
@Override
public int getCount() {
return arrayList.size();
}
@Override
public VideoYoutube getItem(int position) {
return arrayList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder = null;
//Check if it's on memory
if(vi == null) {
//The view is not a recycled one: we have to inflate
vi = inflater.inflate(R.layout.list_row_search, parent, false);
holder = new ViewHolder();
holder.video_title = (TextView)vi.findViewById(R.id.title);
holder.button_play = (Button)vi.findViewById(R.id.button_play);
holder.button_show = (Button)vi.findViewById(R.id.button_show);
holder.button_play.setOnClickListener(this);
holder.button_show.setOnClickListener(this);
vi.setTag(holder);
}
else {
// View recycled !
// no need to inflate
// no need to findViews by id
holder = (ViewHolder) vi.getTag();
}
Object o = getItem(position);
//Set video information
holder.video_title.setText(o.getYtTitle());
return vi;
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.button_play:
Log.d(TAG, "Play: " + v.getId());
break;
case R.id.button_show:
Log.d(TAG, "Show: " + v.getId());
break;
}
}
}
答案 0 :(得分:1)
据我了解,您可以使用:
private ListView mListView;
//Method Constructor
mListView = l;
@Override
public void onClick(View v) {
int position;
switch(v.getId()){
case R.id.button_play:
position = mListView.getPositionForView((View) v.getParent());
Log.d(TAG, "Clicked: " + position);
//search in your arrayList with the position that you'll get
break;
}
}
答案 1 :(得分:0)
您可以为需要数据的按钮设置标记,例如项目ID或位置。然后你可以在点击监听器中得到你需要的东西,如:
public View getView(int position, View convertView, ViewGroup parent) {
...
Object o = getItem(position);
//Set video information
holder.video_title.setText(o.getYtTitle());
holder.button_play.setTag(position);
holder.button_show.setTag(position);
return vi;
}
...
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.button_play:
Object o = getItem((int) v.getTag())
Log.d(TAG, "Play: " + o.getYtTitle());
break;
case R.id.button_show:
Object o = getItem((int) v.getTag())
Log.d(TAG, "Show: " + o.getYtTitle());
break;
}
}