2

我有课

public class User
{
   UUID id;
   String name;
}

我想将这个传递给 ListView:仅列出并显示“名称”。但是当列表视图中的项目将被选中时,我想知道所选项目的“id”。

4

2 回答 2

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

        }
    });
于 2012-09-05T16:55:01.010 回答
1

将对象存储到数组列表中,比如

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();
}
}
于 2012-09-05T16:46:06.650 回答