[英]Android ListView Checkbox Selection
我在这里有两个问题。
1)如何填充我的ListView以便显示字符串,但是当选择项目时,不可见的id值(来自电话联系人的联系人ID)是实际使用的值?
2)我有一个ListView,它使用multipleChoice模式进行项目选择。 它的名字来自我的联系人列表。 当我在ListView中选择一个项目时,我希望所选项目触发对我的SqLite例程的调用,以将该值存储到数据库记录中。 在列表视图中检查项目时如何触发此事件?
这是我的布局XML;
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="@+id/lvContacts"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:choiceMode="multipleChoice"
/>
</LinearLayout>
这是我用来填充ListView的代码;
private void fillData() {
final ArrayList<String> contacts = new ArrayList<String>();
// Let's set our local variable to a reference to our listview control
// in the view.
lvContacts = (ListView) findViewById(R.id.lvContacts);
String[] proj_2 = new String[] {Data._ID, Phone.DISPLAY_NAME, CommonDataKinds.Phone.TYPE};
cursor = managedQuery(Phone.CONTENT_URI, proj_2, null, null, null);
while(cursor.moveToNext()) {
// Only add contacts that have mobile number entries
if ( cursor.getInt(2) == Phone.TYPE_MOBILE ) {
String name = cursor.getString(1);
contacts.add(name);
}
}
// Make the array adapter for the listview.
final ArrayAdapter<String> aa;
aa = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice,
contacts);
// Let's sort our resulting data alphabetically.
aa.sort(new Comparator<String>() {
public int compare(String object1, String object2) {
return object1.compareTo(object2);
};
});
// Give the list of contacts over to the list view now.
lvContacts.setAdapter(aa);
}
我原本希望能够为每个选中的项目使用类似onClick事件的东西,但是没有取得任何进展。
任何帮助都会非常感激。 谢谢。
我认为解决方案的问题是使用自定义列表适配器每个项目包括联系人姓名和联系人ID,这里是详细信息:
1)尝试创建自定义联系人项目bean包括2个属性:contactID,contactName
public class contactItem{
private long contactID;
private String contactName;
//...
}
创建CustomContactAdapter:
public class CustomContactAdapter extends ArrayAdapter<contactItem>{
ArrayList<contactItem> itemList = null;
//Constructor
public CustomContactAdapter (Context context, int MessagewResourceId,
ArrayList<contactItem> objects, Handler handler) {
//Save objects and get LayoutInflater
itemList = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
final ReceiveMailStruct contact= items.get(position);
if (contact!= null) {
view = inflater.inflate(R.layout.layout_display_contact_item, null);
//Set view for contact here
}
}
}
搜索自定义适配器以获取更多信
2)要在ListView处理单击事件,您必须为listitem注册一个处理程序:步骤1:将处理程序注册到List项目:
lvContacts.setOnItemClickListener(new HandlerListClickEvent());
第二步:点击项目时实施进程(勾选/取消选中)
class HandlerListClickEvent implements OnItemClickListener {
public void onItemClick( AdapterView<?> adapter, View view, int position, long id ) {
//Get contact ID here base on item position
}
希望它有所帮助,问候,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.