点击列表视图时,我在获取正确的id值时遇到了一些麻烦。
我制作了一个自定义适配器,因为我从SQLite数据中提取,我得到正确的文本,但当我点击一行时,我得到一个0索引ID,这不是我想要的。
我也在使用Sugar ORM,所以我不确定这是否需要我的一些特殊工作才能获得id字段。
我不确定在代码方面我应该向您展示什么,所以无论您认为什么都会对您有所帮助,请告诉我,我会发布它。
由于
BoardArrayAdapter adapter = new BoardArrayAdapter(this, boards);
setListAdapter(adapter);
ListView lv = getListView();
registerForContextMenu(lv);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Board ID " + id, Toast.LENGTH_SHORT).show();
}
});
答案 0 :(得分:3)
您需要覆盖适配器中的getItemId()
方法。
根据SugarORM文档,您可以调用getid()
来返回db id。
ArrayList<Object> data;
@Override
public long getItemId(int position) {
return data.get(position).getid();
}
答案 1 :(得分:1)
这就是我在我的项目中使用的方式(使用SQLite和CustomListView)。
getData方法
public void getData(View view, long id)
{
//storing the ID into a public static variable and converting to int
CLIENTE_ID = (int)id;
//When the user touches on the field in the listview, I get the touched field's name and email
TextView textViewnome = (TextView) view.findViewById(R.id.tv_cliente_nome);
TextView textViewemail = (TextView) view.findViewById(R.id.tv_cliente_email);
//Stores both name and email of the touched field
String nome = textViewnome.getText().toString();
String email = textViewemail.getText().toString();
//store into static variable
CLIENTE_NOME = nome;
CLIENTE_EMAIL = email;
}
onCreate中的:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
getData(view, id);
Log.d("myClass", "ID: " + view.getId());
}
});
我希望它有所帮助! :)