0

谁能告诉我如何获取自定义视图列表中选中行的值?例如,我的代码有一个自定义视图列表,其中包含两个文本视图和一个复选框。每当用户检查一行并点击提交按钮时,我需要检索两个文本视图中的信息。

代码是

 public class contacts extends Activity implements OnItemClickListener {
        static final String TAG = "contacts";
        ArrayList<String> contactName = new ArrayList<String>();
        ArrayList<String> contactNumber = new ArrayList<String>();

        MyAdapter myAdapter;
        Button AddNumber;
        String numberIntent;
        View vi;
        ListView listView;

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

            getAllContacts(this.getContentResolver());
            listView = (ListView) findViewById(R.id.lists);
            myAdapter = new MyAdapter();
            listView.setAdapter(myAdapter);

            listView.setItemsCanFocus(false);
            listView.setTextFilterEnabled(true);
            // adding
            AddNumber = (Button) findViewById(R.id.AddNumbers);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {



                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                        long arg3) {
                    Object listItem = listView.getItemAtPosition(0);
                    Log.d(TAG,"listView listener" + listItem);
                }
            });

            AddNumber.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    StringBuilder checkedContacts = new StringBuilder();
                    Log.d(TAG, "onClick" + myAdapter.mCheckStates.size());
                    for (int i = 0; i < contactName.size(); i++)

                    {
                        if (myAdapter.mCheckStates.get(i) == true) {
                            checkedContacts.append(contactName.get(i).toString());
                            checkedContacts.append("\n");

                        } else {
                            Log.d(TAG, "No OnClick" + contactName.get(i).toString());
                        }

                    }

                    Toast.makeText(contacts.this, checkedContacts,
                            Toast.LENGTH_LONG).show();
                     ArrayList<String> checkboxArray = new ArrayList<String>();
                     myAdapter.mCheckStates = listView.getCheckedItemPositions();
                     Log.d(TAG, "Sparse" + myAdapter.mCheckStates);
                     for (int i = 0; i < myAdapter.mCheckStates.size(); i++) {
                     int position = myAdapter.mCheckStates.keyAt(i);
                     boolean bool = myAdapter.mCheckStates.valueAt(position);
                                     Log.d(TAG, "Sparse2" + myAdapter.mCheckStates);
                     }
                     String[] outputStrArr = new String[checkboxArray.size()];

                     for (int i = 0; i < checkboxArray.size(); i++) {
                     outputStrArr[i] = checkboxArray.get(i);


                     }

                }
            });

        }

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            myAdapter.toggle(arg2);
        }

        public void getAllContacts(ContentResolver cr) {

            Cursor cursor = cr.query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
                    null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
                            + " COLLATE LOCALIZED ASC");
            while (cursor.moveToNext()) {
                String name = cursor
                        .getString(cursor
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                String phoneNumber = cursor
                        .getString(cursor
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                Log.d(TAG, "getAllContacts" + phoneNumber);
                contactName.add(name);
                contactNumber.add(phoneNumber);

            }

            cursor.close();
            Intent in = new Intent(this, TrackLogic.class);
            in.putExtra("contact", contactName.toArray());
            Log.d(TAG, "Intent????" + contactName);
            in.putExtra("contact1", contactNumber.toArray());
        }

        class MyAdapter extends BaseAdapter implements
                CompoundButton.OnCheckedChangeListener {
            private SparseBooleanArray mCheckStates;
            LayoutInflater mInflater;
            TextView phoneView, contactView;
            CheckBox checkBox;

            MyAdapter() {
                mCheckStates = new SparseBooleanArray(contactName.size());
                mInflater = (LayoutInflater) contacts.this
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            }

            @Override
            public int getCount() {
                return contactName.size();
            }

            @Override
            public Object getItem(int position) {
                return position;
            }

            @Override
            public long getItemId(int position) {

                return 0;
            }

            @Override
            public View getView(final int position, View convertView,
                    ViewGroup parent) {
                vi = convertView;
                if (convertView == null)
                    vi = mInflater.inflate(R.layout.row, null);
                contactView = (TextView) vi.findViewById(R.id.contact_name);
                phoneView = (TextView) vi.findViewById(R.id.phone_number);
                checkBox = (CheckBox) vi.findViewById(R.id.checkBox_id);
                contactView.setText(contactName.get(position));
                phoneView.setText(contactNumber.get(position));
                checkBox.setTag(position);
                checkBox.setChecked(mCheckStates.get(position, false));
                checkBox.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);
                Log.d(TAG, "setChecked");
                notifyDataSetChanged();
            }

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

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {


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

我似乎无法弄清楚,现在它对我来说真的很累。任何帮助都非常感谢..谢谢。

4

3 回答 3

0

更新

检查此链接这正是您想要做的

在你的按钮onclick方法中试试这个

SparseBooleanArray checkedItems = listView.getCheckedItemPositions();
if (checkedItems != null) {
    for (int i=0; i<checkedItems.size(); i++) {
        if (checkedItems.valueAt(i)) {
            String item = listView.getAdapter().getItem(
                                  checkedItems.keyAt(i)).toString();
            Log.i(TAG,item + " was selected");
        }
    }
}

在你的情况下,你也可以这样做

for (int i = 0; i < myAdapter.getCount(); i++)
     {
        if (myAdapter.isChecked(i))
        {
             Toast.makeText(context,
              "Item at position " +i+" is Checked!!",
              Toast.LENGTH_SHORT).show();
         }
      }

尝试将侦听器添加到自定义适配器中的复选框,请参见此处的示例

于 2013-06-24T04:10:32.010 回答
0

愿这对你有帮助

调用isChecked()复选框以获取其状态。

如果要计算选中复选框的数量,则可以将复选框存储在一个中ArrayList并循环遍历...

编辑

getView()方法内部,您必须OnCheckedChangeListenerCheckBox.

例如:

CheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener()

{

    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {
        if ( isChecked )
        {
            // you should create a reference of the textviews here before you use it..

            String value1 = Textview1.getText();
            String value2 = Textview2.getText();

        }

    }
});
于 2013-06-24T04:19:56.657 回答
0

https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M

您的自定义适配器必须实现CompoundButton.OnCheckedChangeListener。使用 aSparseBooleanArray获取列表中的选中项目。

然后

     cb.setChecked(mCheckStates.get(position, false)); 
     cb.setOnCheckedChangeListener(this);

然后使用选中状态将文本设置为复选框

      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
    if(isChecked)
    {
    buttonView.setText("Hello");
    }
    else
    {
        buttonView.setText("");
    }
     mCheckStates.put((Integer) buttonView.getTag(), isChecked);    

}

例子 :

public class MainActivity extends Activity implements OnItemClickListener{


List<String> name1 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
MyAdapter ma ;
Button select
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    setContentView(R.layout.activity_main);

    getAllCallLogs(this.getContentResolver());
    ListView lv= (ListView) findViewById(R.id.lv);
     ma = new MyAdapter();
    lv.setAdapter(ma);
    lv.setOnItemClickListener(this); 
    lv.setItemsCanFocus(false);
    lv.setTextFilterEnabled(true);
    // adding
    select = (Button) findViewById(R.id.button1);
    select.setOnClickListener(new OnClickListener()
    {

        @Override
        public void onClick(View v) {
              StringBuilder checkedcontacts= new StringBuilder();
            System.out.println(".............."+ma.mCheckStates.size());
            for(int i = 0; i < name1.size(); i++)

                {
                if(ma.mCheckStates.get(i)==true)
                {

                     checkedcontacts.append(name1.get(i).toString());
                     checkedcontacts.append("\n");
                }
                else
                {
                    System.out.println("..Not Checked......"+name1.get(i).toString());
                }

            }
                  Toast.MakeText(MainActivity.this,checkedcontacts,1000).show();
        }       
    });



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

public  void getAllCallLogs(ContentResolver cr) {

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

    phones.close();
 }
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{  private SparseBooleanArray mCheckStates;
   LayoutInflater mInflater;
    TextView tv1,tv;
    CheckBox cb;
    MyAdapter()
    {
        mCheckStates = new SparseBooleanArray(name1.size());
        mInflater = (LayoutInflater)MainActivity.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.row, null); 
         TextView tv= (TextView) vi.findViewById(R.id.textView1);
         tv1= (TextView) vi.findViewById(R.id.textView2);
         cb = (CheckBox) vi.findViewById(R.id.checkBox1);
         tv.setText("Name :"+ name1.get(position));
         tv1.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);
            System.out.println("hello...........");
            notifyDataSetChanged();
        }

        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);    

    }

}

 }

activity_main.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:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_above="@+id/button1"

       android:id="@+id/lv"/>

     <Button
         android:id="@+id/button1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentBottom="true"
         android:layout_centerHorizontal="true"
         android:text="Select" />

</RelativeLayout>

行.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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="34dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/checkBox1"
        android:layout_alignLeft="@+id/textView1"
        android:text="TextView" />

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:layout_marginRight="22dp"
        android:layout_marginTop="23dp" />

</RelativeLayout>

您可以勾选复选框并单击底部的按钮,选中的项目将显示在吐司中。

根据您的要求修改上述内容。

于 2013-06-24T05:09:43.247 回答