Android:带有复选框问题的 ListView

标签 android android-listview android-checkbox

我有一个 LinearLayout,我在其中将 phone contacts 填充到布局中,现在我放置了一个 checkbox,我想 < strong>实现 checkboxes 的多重选择,我想选择多个联系人,当我保存(点击保存按钮)时,这些联系人应该保存在我的另一个布局中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" 
    android:paddingTop="5dp"
    android:paddingBottom="5dp"
    android:id="@+id/profilelayout" >

     <ImageView
          android:id="@+id/photo"
          android:layout_width="68dp"
          android:layout_height="51dp" >
     </ImageView>

     <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

       <TextView android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="15dp"
        android:textStyle="bold"
        android:textColor="#000000"/>

       <CheckBox
           android:id="@+id/checkBox1"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"         
           android:layout_gravity="right"
           android:focusable="false"/>

      <TextView android:id="@+id/contactno"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        />
      <TextView android:id="@+id/emailId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        />      

</LinearLayout>
</LinearLayout>

关于我如何实现这一点的任何建议,以及当我只选中 checkbox 时,其他几行也会被检查如何避免这种情况。感谢您的帮助。

最佳答案

使用这个

   public class PlanetsActivity extends Activity {
    private ListView mainListView;
    private Contact[] contact_read;
    private Cursor mCursor;
    private ArrayAdapter<Contact> listAdapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Find the ListView resource.
    mainListView = (ListView) findViewById(R.id.mainListView);

    mainListView
            .setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View item,
                        int position, long id) {
                    Contact planet = listAdapter.getItem(position);
                    planet.toggleChecked();
                    ContactViewHolder viewHolder = (ContactViewHolder) item
                            .getTag();
                    viewHolder.getCheckBox().setChecked(planet.isChecked());
                }
            });

    // Throw Query and fetch the contacts.

    String[] projection = new String[] { Contacts.HAS_PHONE_NUMBER,
            Contacts._ID, Contacts.DISPLAY_NAME };

    mCursor = managedQuery(Contacts.CONTENT_URI, projection,
            Contacts.HAS_PHONE_NUMBER + "=?", new String[] { "1" },
            Contacts.DISPLAY_NAME);

    if (mCursor != null) {
        mCursor.moveToFirst();
        contact_read = new Contact[mCursor.getCount()];

        // Add Contacts to the Array

        int j = 0;
        do {

            contact_read[j] = new Contact(mCursor.getString(mCursor
                    .getColumnIndex(Contacts.DISPLAY_NAME)));
            j++;
        } while (mCursor.moveToNext());

    } else {
        System.out.println("Cursor is NULL");
    }

    // Add Contact Class to the Arraylist

    ArrayList<Contact> planetList = new ArrayList<Contact>();
    planetList.addAll(Arrays.asList(contact_read));

    // Set our custom array adapter as the ListView's adapter.
    listAdapter = new ContactArrayAdapter(this, planetList);
    mainListView.setAdapter(listAdapter);
}

    /** Holds Contact data. */
    @SuppressWarnings("unused")
    private static class Contact {
    private String name = "";
    private boolean checked = false;

    public Contact() {
    }

    public Contact(String name) {
        this.name = name;
    }

    public Contact(String name, boolean checked) {
        this.name = name;
        this.checked = checked;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isChecked() {
        return checked;
    }

    public void setChecked(boolean checked) {
        this.checked = checked;
    }

    public String toString() {
        return name;
    }

    public void toggleChecked() {
        checked = !checked;
    }
}

    /** Holds child views for one row. */
    @SuppressWarnings("unused")
    private static class ContactViewHolder {
    private CheckBox checkBox;
    private TextView textView;

    public ContactViewHolder() {
    }

    public ContactViewHolder(TextView textView, CheckBox checkBox) {
        this.checkBox = checkBox;
        this.textView = textView;
    }

    public CheckBox getCheckBox() {
        return checkBox;
    }

    public void setCheckBox(CheckBox checkBox) {
        this.checkBox = checkBox;
    }

    public TextView getTextView() {
        return textView;
    }

    public void setTextView(TextView textView) {
        this.textView = textView;
    }
}

    /** Custom adapter for displaying an array of Contact objects. */
    private static class ContactArrayAdapter extends ArrayAdapter<Contact> {

    private LayoutInflater inflater;

    public ContactArrayAdapter(Context context, List<Contact> planetList) {
        super(context, R.layout.simplerow, R.id.rowTextView, planetList);
        // Cache the LayoutInflate to avoid asking for a new one each time.
        inflater = LayoutInflater.from(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Contact to display
        Contact planet = (Contact) this.getItem(position);
        System.out.println(String.valueOf(position));

        // The child views in each row.
        CheckBox checkBox;
        TextView textView;

        // Create a new row view
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.simplerow, null);

            // Find the child views.
            textView = (TextView) convertView
                    .findViewById(R.id.rowTextView);
            checkBox = (CheckBox) convertView.findViewById(R.id.CheckBox01);

            // Optimization: Tag the row with it's child views, so we don't
            // have to
            // call findViewById() later when we reuse the row.
            convertView.setTag(new ContactViewHolder(textView, checkBox));

            // If CheckBox is toggled, update the Contact it is tagged with.
            checkBox.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    CheckBox cb = (CheckBox) v;
                    Contact contact = (Contact) cb.getTag();
                    contact.setChecked(cb.isChecked());
                }
            });
        }
        // Reuse existing row view
        else {
            // Because we use a ViewHolder, we avoid having to call
            // findViewById().
            ContactViewHolder viewHolder = (ContactViewHolder) convertView
                    .getTag();
            checkBox = viewHolder.getCheckBox();
            textView = viewHolder.getTextView();
        }

        // Tag the CheckBox with the Contact it is displaying, so that we
        // can
        // access the Contact in onClick() when the CheckBox is toggled.
        checkBox.setTag(planet);

        // Display Contact data
        checkBox.setChecked(planet.isChecked());
        textView.setText(planet.getName());

        return convertView;
    }

   }

   public Object onRetainNonConfigurationInstance() {
        return contact_read;
    }
}

关于Android:带有复选框问题的 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14117983/

相关文章:

android - onLeScan 在发现蓝牙文件设备时调用了两次

android - 从使用 Picasso 加载的 ImageView 获取位图

java - RecyclerView更新项目的文本和图标OnClick

android - 是否可以使用 CheckBox 设置 `error` 字符串?

java - 在 Android Studio 中将 JSON 解析为 List [java]

android - 我在哪里放置代码以将请求传递到 Android In App Billing 中的 In-app Billing 服务?

android - ListView 中 TextView 的文本未被省略

android-layout - ListView选择自定义颜色

java - 更改 gridview 适配器类中所有复选框的可见性

android - 如何获取可以选中的复选框的数量?