Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/219.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何为填充的listview中的每个联系人链接复选框?_Android_Listview_Checkbox - Fatal编程技术网

Android 如何为填充的listview中的每个联系人链接复选框?

Android 如何为填充的listview中的每个联系人链接复选框?,android,listview,checkbox,Android,Listview,Checkbox,这个问题一直困扰着我。我有一个列表视图,其中包含: ImageView/contactName/TextView/CheckBox 通过从SimpleCorsOrAdapter读取手机上的联系人,可以填充列表视图中的联系人姓名。应用程序运行时会显示All for元素,但我遇到的问题是将复选框连接到列表中相应的项 通过一些研究,我发现我必须使用getView()将复选框与列表中的项目链接起来,但通过实践,我似乎无法使其正常工作。此外,我尝试过的示例中没有一个真正解释了如何应用getView()。我

这个问题一直困扰着我。我有一个列表视图,其中包含:

ImageView/contactName/TextView/CheckBox

通过从SimpleCorsOrAdapter读取手机上的联系人,可以填充列表视图中的联系人姓名。应用程序运行时会显示All for元素,但我遇到的问题是将复选框连接到列表中相应的项

通过一些研究,我发现我必须使用getView()将复选框与列表中的项目链接起来,但通过实践,我似乎无法使其正常工作。此外,我尝试过的示例中没有一个真正解释了如何应用getView()。我工作过的最完整的例子如下:

问题在于,它读取并用我的联系人填充我的listview:

private void populateContactList() {
    // Build adapter with contact entries
    Cursor cursor = getContacts();
    String[] fields = new String[] {
            ContactsContract.Data.DISPLAY_NAME       
    };

    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contact_entry, cursor,
            fields, new int[] {R.id.contactEntryText});    
    lv.setAdapter(adapter);        
} // END POPULATECONTACTLIST


private Cursor getContacts()
{ 
    // Run query
    Uri uri = ContactsContract.Contacts.CONTENT_URI;
    String[] projection = new String[] {
            ContactsContract.Contacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME
    };
    String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" +
            (chkboxAllVisible ? "0" : "1") + "'";
    String[] selectionArgs = null;
    String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";

    return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
} // END GETCONTACTS 

如何将每个复选框链接到我的listview中对应的联系人项目?

不要使用自定义列表视图。您可以使用默认的listview,该列表视图具有复选框功能,但对于列表视图属性,每个列表项目只能使用一个。listview有复选框您只需要设置multiselection列表视图

编辑1:

请点击链接:

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setListAdapter(新阵列适配器)(此,
android.R.layout.simple_list_item_多项选择,流派);
最终ListView ListView=getListView();
setItemsCanFocus(false);
listView.setChoiceMode(listView.CHOICE\u MODE\u MULTIPLE);
}
请参阅此特定代码,您仅将文本源(在字段中)与实际文本视图(R.id.contactEntryText)进行映射。。。同样地,你需要添加。。。为复选框映射的另一个字段和相应视图

或者最好制作一个CustomAdapter,您可以找到关于它的教程并覆盖getView方法,这样您就可以获得最大的灵活性。您可以做任何您想做的事情


这可能会有帮助:

好的,我已经为您创建了一个测试项目,请尝试理解代码,如果您有任何问题,请询问,我将尝试帮助您

这是我的ONCREATE活动函数

super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<String> elements = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
    elements.add("elements " + i);
}

CheckBox master_cb = new CheckBox(getApplicationContext());
master_cb.setText("Check All");
//HERE IS THE LIST VIEW WHICH I HAVE CREATED IN MY XML FILE.
ListView lv = (ListView) findViewById(R.id.listView1);
//HERE I AM CREATING CUSTOM ADAPTER OBJECT.
my_custom_adapter adapter = new my_custom_adapter(this, android.R.layout.simple_list_item_1, elements);
lv.addHeaderView(master_cb);
lv.setAdapter(adapter);
master_cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        Intent my_intent = new Intent("master_check_change");
        my_intent.putExtra("check_value", isChecked);
        sendBroadcast(my_intent);
    }
});

还有一些相应的修改

原因是我需要对复选框进行编程,以便与每个联系人一起工作。另外,我在listview之外有一个复选框,用作主复选框。选中主复选框后,其任务是选中列表中的所有复选框。要测试列表中的复选框,请尝试实现LogCat以显示选中的项目。当您按照此操作时会出现一些问题复选框将在scrollingOk上自动选中。我应用了您的示例,但在我的示例上进行测试之前,我是否需要在清单中为您的自定义类设置接收器?或者我可以把它作为一项常规活动吗?谢谢你的耐心。非常感谢。:)不,您不需要在清单文件中设置广播接收器。只需添加它,您不需要做任何事情,只需在新项目中创建受尊重的文件和类并运行它。主复选框可以工作!不过我有几个问题。如何将元素数设置为联系人数的大小?super(上下文、类型、元素)无论您将在此传递什么作为“元素”,都将创建大量行。。所以只需将所有联系人作为arraylist传递,它就会自动创建与联系人数量相等的行。在我的示例中,没有行是elements.size()。您已经自定义了适配器,因此可以传递适配器中的任何列表。不要将自定义适配器更改为字符串,并将字符串传递到自定义适配器的超级。它可以接受arraylist和string数组。。
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contact_entry, cursor,
        fields, new int[] {R.id.contactEntryText});
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<String> elements = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
    elements.add("elements " + i);
}

CheckBox master_cb = new CheckBox(getApplicationContext());
master_cb.setText("Check All");
//HERE IS THE LIST VIEW WHICH I HAVE CREATED IN MY XML FILE.
ListView lv = (ListView) findViewById(R.id.listView1);
//HERE I AM CREATING CUSTOM ADAPTER OBJECT.
my_custom_adapter adapter = new my_custom_adapter(this, android.R.layout.simple_list_item_1, elements);
lv.addHeaderView(master_cb);
lv.setAdapter(adapter);
master_cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        Intent my_intent = new Intent("master_check_change");
        my_intent.putExtra("check_value", isChecked);
        sendBroadcast(my_intent);
    }
});
public class my_custom_adapter extends ArrayAdapter<String> {
    private Context context                     = null;
    ArrayList<String>  elements                 = null;
    private ArrayList<Boolean> itemChecked      = null;

    public my_custom_adapter(Context context, int type, ArrayList<String>  elements)
    {
        super(context, type, elements);
        this.elements =  elements;
        this.context = context;
        itemChecked = new ArrayList<Boolean>();
        BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals("master_check_change")) {
                    boolean check_value = intent.getBooleanExtra("check_value", false);
                    set_checked(check_value);
                    notifyDataSetChanged();
                }
            }
        };
        context.registerReceiver(receiver, new IntentFilter("master_check_change"));
        set_checked(false);
    }

    // AS EVERY TIME LISTVIEW INFLATE YOUR VIEWS WHEN YOU MOVE THEM SO YOU NEED TO SAVE ALL OF YOUR CHECKBOX STATES IN SOME ARRAYLIST OTHERWISE IT WILL SET ANY DEFAULT VALUE.
    private void set_checked(boolean is_checked)
    {
        for (int i=0; i < elements.size(); i++) {
            itemChecked.add(i, is_checked);
        }
    }

    //THIS IS SIMPLY A CLASS VIEW WILL HOLD DIFFERENT VIEWS OF YOUR ROW.
    static class ViewHolder
    {
        public TextView tv;
        public CheckBox cb;
        public ImageView iv;
    }

    @Override
    public View getView (final int position, View convertView, ViewGroup parent)
    {
        View rowView = convertView;
        ViewHolder holder = null;

        if (rowView == null) {
            LayoutInflater inflater = (LayoutInflater)context.getSystemService(
                                               Context.LAYOUT_INFLATER_SERVICE);
            // HERE I AM INFLATING LISTVIEW LAYOUT.
            rowView = inflater.inflate(R.layout.inflated_layout, null, false);
            holder = new ViewHolder();
            holder.cb = (CheckBox) rowView.findViewById(R.id.checkBox1);
            holder.tv = (TextView) rowView.findViewById(R.id.textView1);
            holder.iv = (ImageView) rowView.findViewById(R.id.imageView1);
            rowView.setTag(holder);

        } else {
            holder = (ViewHolder) rowView.getTag();
        }

        if (holder != null) {
            holder.tv.setText(elements.get(position));

            holder.cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView,
                                             boolean isChecked) {
                    itemChecked.set(position, isChecked);
                }
            });

            if(position < itemChecked.size()) {
                holder.cb.setChecked(itemChecked.get(position));
            }
        }
        return rowView;
    }
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >

    </ListView>

</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="17dp" />




    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toLeftOf="@+id/checkBox1"
        android:layout_toRightOf="@+id/imageView1"
        android:singleLine="true"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />


    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>
    String[] elements = new String[10];
    for (int i = 0; i < 10; i++) {
        elements[i] = "elements " + i;
    }
public my_custom_adapter(Context context, int type, String[]  elements)