只选中那个复选框,这些复选框在我们面前

时间:2013-09-07 11:57:05

标签: java android android-layout

我有一个按钮来选中所有复选框但我只有一个问题是选中了复选框,它们在我们前面向下滚动其他复选框未被选中

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;

import com.example.callblockerapp.R;
import com.utills.DbHelper;

public class AddFromContacts extends Activity implements OnItemClickListener {

List<String> name1 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
ContactsAdapter ma;
ListView lv;
private Button select, btnCancelFromContacts, btnAllFromContacts;

DbHelper db = new DbHelper(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_from_contacts);

    getAllContacts(this.getContentResolver());
    lv = (ListView) findViewById(R.id.ContactlistView);
    ma = new ContactsAdapter();
    lv.setAdapter(ma);
    lv.setOnItemClickListener(this);
    lv.setItemsCanFocus(false);
    lv.setTextFilterEnabled(true);
    // adding
    select = (Button) findViewById(R.id.getSelected);
    btnCancelFromContacts = (Button) (findViewById(R.id.btnCancelFromContacts));
    btnCancelFromContacts.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            finish();
        }
    });
    select.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // StringBuilder checkedcontacts = new StringBuilder();
            String name, phoneNumber;
            for (int i = 0; i < name1.size(); i++)

            {
                if (ma.mCheckStates.get(i) == true) {
                    // checkedcontacts.append(name1.get(i).toString());
                    // checkedcontacts.append("\n");
                    name = name1.get(i).toString();
                    phoneNumber = phno1.get(i).toString();
                    phoneNumber = phoneNumber.replace("-", "");
                    Log.e("", "Checked Name :- " + name
                            + "\nChecked Phone Number :- " +             phoneNumber);
                    db.addBlockedNumber(phoneNumber, name);

                    finish();

                } else {

                }
            }

            // Toast.makeText(AddFromContacts.this, checkedcontacts,
            // Toast.LENGTH_LONG).show();
        }
    });

    btnAllFromContacts = (Button) findViewById(R.id.btnAllFromContacts);
    btnAllFromContacts.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            for (int i = 0; i < lv.getChildCount(); i++) {
                ViewGroup item = (ViewGroup) lv.getChildAt(i);
                CheckBox checkbox = (CheckBox) item
                        .findViewById(R.id.checkBox);
            //  if (!checkbox.isChecked()) {
                    checkbox.setChecked(true);
                    btnAllFromContacts.setText("Uncheck All");
        //      } else if (checkbox.isChecked()) {
        //          checkbox.setChecked(false);
        //          btnAllFromContacts.setText("Select All");
        //      }

            }

        }
    });

}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub
    ma.toggle(arg2);
}

public void getAllContacts(ContentResolver cr) {

    Cursor phones = cr.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
            null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
                    + " ASC");
    while (phones.moveToNext()) {
        String name = phones
                .getString(phones
                          .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String phoneNumber = phones
                .getString(phones
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        name1.add(name);
        phno1.add(phoneNumber);

    }

    phones.close();
}

class ContactsAdapter extends BaseAdapter implements
        CompoundButton.OnCheckedChangeListener {
    private SparseBooleanArray mCheckStates;
    LayoutInflater mInflater;
    TextView name, txtNumber;
    CheckBox cb;

    ContactsAdapter() {
        mCheckStates = new SparseBooleanArray(name1.size());
        mInflater = (LayoutInflater) AddFromContacts.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return name1.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub

        return 0;
    }

    @Override
    public View getView(final int position, View convertView,
            ViewGroup parent) {
        // TODO Auto-generated method stub
        View vi = convertView;
        if (convertView == null)
            vi = mInflater.inflate(R.layout.add_from_contacts_row, null);
        txtNumber = (TextView) vi.findViewById(R.id.txtNumber);
        name = (TextView) vi.findViewById(R.id.name);
        cb = (CheckBox) vi.findViewById(R.id.checkBox);
        txtNumber.setText("Name :" + name1.get(position));
        name.setText("Phone No :" + phno1.get(position));
        cb.setTag(position);
        cb.setChecked(mCheckStates.get(position, false));
        cb.setOnCheckedChangeListener(this);

        return vi;
    }

    public boolean isChecked(int position) {
        return mCheckStates.get(position, false);
    }

    public void setChecked(int position, boolean isChecked) {
        mCheckStates.put(position, isChecked);
    }

    public void toggle(int position) {
        setChecked(position, !isChecked(position));
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView,
            boolean isChecked) {
        // TODO Auto-generated method stub

        mCheckStates.put((Integer) buttonView.getTag(), isChecked);
    }
}
}

xml文件add_from_contacts.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<ListView
    android:id="@+id/ContactlistView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:background="#ffbdbdbd"
    android:orientation="horizontal"
    android:paddingTop="2.5dip" >

    <Button
        android:id="@+id/btnAllFromContacts"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1.0"
        android:gravity="center"
        android:text="Select All"
        android:textSize="14.0dip" />

    <Button
        android:id="@+id/getSelected"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1.0"
        android:gravity="center"
        android:text="Add Contact"
        android:textAppearance="?android:textAppearanceMedium"
        android:textSize="14.0dip" />

    <Button
        android:id="@+id/btnCancelFromContacts"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1.0"
        android:gravity="center"
        android:text="Cancel"
        android:textSize="14.0dip" />
</LinearLayout>

</RelativeLayout>

另一个xml文件add_from_contacts_row.xml

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

<TextView
    android:id="@+id/txtNumber"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/txtNumber" />

<CheckBox
    android:id="@+id/checkBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true" />

</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

我可以建议一个简单的方法吗?假设我有class AddFromContacts的全局变量as,

public static boolean checked=false;

现在,在按钮单击内部(按钮选择/取消全选),保留您按原样写的循环。包括以下内容。

if(checked)
   checked=false;
else
   checked=true;

然后在适配器getView()内,

cb.setChecked(AddFromContacts.checked);

例如:为我工作

public class MainActivity extends Activity {
ListView lv;
Button b1;
boolean checked=false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lv=(ListView) findViewById(R.id.listView1);
    b1=(Button) findViewById(R.id.button1);
    Myadapter adapter=new Myadapter();
    lv.setAdapter(adapter);
    b1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if(checked)
                checked=false;
            else
                checked=true;
             for (int i = 0; i < lv.getChildCount(); i++) {
                    ViewGroup item = (ViewGroup) lv.getChildAt(i);
                    CheckBox checkbox = (CheckBox) item
                            .findViewById(R.id.checkBox1);

                        checkbox.setChecked(checked);
             }
        }
    });
}



class Myadapter extends BaseAdapter{
    CheckBox cb;
     LayoutInflater mInflater;

     public Myadapter() {
         mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return 15;
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return arg0;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
         View vi = convertView;
            if (convertView == null)
                vi = mInflater.inflate(R.layout.item, null);
            cb = (CheckBox) vi.findViewById(R.id.checkBox1);
            cb.setTag(position);
            cb.setChecked(checked);
        return vi;
    }

}


}

另外,我可以看到 public void setChecked(int position, boolean isChecked) 的方法。如果您打算将其调用,请将代码更改为 setChecked(position,mCheckStates.get(position, false));