Android ListView获取物品ID

时间:2015-09-08 18:48:22

标签: android android-listview

在下面的代码中,我正在创建一个字符串数组并拆分字符串以去除ID。而不是这个我想要关联数组,以便我可以从数组中选择项目的ID。任何人都可以帮忙!

MyImage::before {
  content: attr(source url);
}

1 个答案:

答案 0 :(得分:1)

试试这个:

public class YourItem {

    private String title;
    private long id;

    public YourItem(long id, String title){     
        this.setTitle(title);
        this.setId(id);             
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    @Override
    public String toString(){
        return title;
    }
}

像这样调用你的适配器:

YourItem[] data={new YourItem(12,"Item 1"),
                 new YourItem(14,"Item 2")
                 new YourItem(34,"Item 3")
                 new YourItem(56,"Item 4")
                 };


ArrayAdapter<YourItem> adapter = new ArrayAdapter<YourItem>(this,R.layout.learning_path_single_row,R.id.textView,data);

在你的听众中做这样的事情:

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        String title= parent.getItemAtPosition(position).getTitle();
        long id = parent.getItemAtPosition(position).getId()

        Toast.makeText(getApplicationContext(),
                "ID: " + id +" Title: " + title, Toast.LENGTH_LONG)
                .show();


    }
});

我认为应该这样做。