[英]Get position of item in listView with onItemClick on particular object
我有一个ListView,其中包含从外部数据库获得的几个条目。 每个条目都有一个图像按钮和其他对象。 我想知道用户单击图像按钮的列表条目的位置。
是否有可能查看用户单击的巫婆对象的特殊性
this.getALlEntrysListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
JSONObject entryClicked = jsonArray.getJSONObject(position);
? 这段代码在我的MainActivity类中。
我在Adapter类中设置每个条目的特定内容。
仅当用户单击图像按钮时,才能获取jsonArray的位置的另一种可能性?
这是我的适配器类:
public class GetAllEntrysListViewAdapter extends BaseAdapter {
private JSONArray dataArray;
private Activity activity;
private static LayoutInflater inflater = null;
public GetAllEntrysListViewAdapter(JSONArray jsonArray, Activity a) {
this.dataArray = jsonArray;
this.activity = a;
inflater = (LayoutInflater)this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return this.dataArray.length();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//set up convert view if it is not null
ListCell cell;
if (convertView == null) {
convertView = inflater.inflate(R.layout.get_all_entry_list_view_cell, null);
cell = new ListCell();
cell.likes = (TextView) convertView.findViewById(R.id.listViewLikes);
cell.note = (TextView) convertView.findViewById(R.id.listViewNote);
cell.img = (ImageView) convertView.findViewById(R.id.listViewImg);
cell.likeButton = (ImageButton) convertView.findViewById(R.id.likeButton);
convertView.setTag(cell);
}
else {
cell = (ListCell)convertView.getTag();
}
//change data of cell
try {
JSONObject jsonObject = this.dataArray.getJSONObject(position);
cell.likes.setText("Likes: "+ jsonObject.getString("likes"));
cell.note.setText(jsonObject.getString("note"));
String img = jsonObject.getString("image");
if (img.equals("img")) {
cell.img.setImageResource(R.drawable.logo);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return convertView;
}
private class ListCell {
private TextView likes;
private TextView note;
private ImageView img;
public ImageButton likeButton;
}
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout parent = (RelativeLayout)v.getParent();
int position = listView.getPositionForView(parent);
// position in listview
}
});
仅当用户单击图像按钮时,才能获取jsonArray的位置的另一种可能性?
您必须调用setOnClickListener
和ImageButton
。 特别重要的是用position
标记ImageButton
cell.likeButton.setTag(position);
cell.likeButton.setOnClickListener(...);
并在触发onClick
时,检索代表位置的tag
,并通过它获取数据集中的条目
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.