我有课
public class User
{
UUID id;
String name;
}
我想传入ListView:列出并仅显示“name”。 但是当选择列表视图中的项目时,我想知道所选项目的“id”。
答案 0 :(得分:4)
首先,我会创建一个包含两条信息的类。
public class MyItem {
public final String name;
public final String id;
public MyItem(String name, String id) {
this.name = name;
this.id = id;
}
}
然后创建一个可以支持此类的自定义适配器。
public class CustomAdapter extends ArrayAdapter<MyItem> {
private Context context;
private ArrayList<MyItem> items;
private LayoutInflater vi;
public EntryAdapter(Context context,ArrayList<MyItem> items) {
super(context,0, items);
this.context = context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final Item i = items.get(position);
if (i != null) {
v = vi.inflate(R.layout.list_item, null); //custom xml for desired view
//do what ever you need to
}
return v;
}
}
填充MyItem数组,然后使用数组创建自定义适配器。
items = new ArrayList<MyItem>(); // then populate it
myAdapter = new CustomAdapter(this, items);
现在设置ListView并使用OnItemClickListener
myList.setAdapter(myAdapter);
myList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parentView, View view, int position,
long id)
{
((MyItem)myAdapter.getItem(position)).id); //this line gets you the id of the clicked item
}
});
答案 1 :(得分:1)
将对象存储到类似
的arraylist中Arraylist<User> al = new ArrayList<User>();
然后使用
将对象添加到arraylist User user = new User();
user.id = somevalue;
user.name = someNameValue;
al.add(user);
接下来在onitemclick()中点击项目然后使用arraylist项目显示它
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(this, "item clicked is " + arg2+al.get(arg2).id+" "al.get(arg2).name,
Toast.LENGTH_SHORT)
.show();
}
}