如何从listview复选框中获取价值?

时间:2017-02-20 07:30:59

标签: android listview checkbox

我在使用listview时有点麻烦,我希望获得listview的值,当单击按钮时,会选中其复选框。到目前为止,我已经创建了一个带有复选框的列表视图,并从mysql中获取了所有值,但是我无法获得已检查的列表视图的值。

这是我的班级

public class ListViewMultipleSelectionActivity extends Activity{
    Button button;
    String myJSON;

    private static final String TAG_NAME = "cat_name";

    JSONArray peoples = null;

    ArrayList<HashMap<String, String>> personList;

    ListView list1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        personList = new ArrayList<HashMap<String,String>>();
        list1 = (ListView) findViewById(R.id.list);
        button = (Button)findViewById(R.id.testbutton);
        getlat();



        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {


            }
        });

    }

    public void getlat(){
        class GetDataJSON extends AsyncTask<String, Void, String> {
            public void onPreExecute() {
            }
            @Override
            protected String doInBackground(String... params) {

                InputStream inputStream = null;
                String result = null;
                try {

                    URL url = new URL("http://xxxxxxxxxxxx/category.php");

                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setReadTimeout(15000 /* milliseconds */);
                    conn.setConnectTimeout(15000 /* milliseconds */);
                    conn.setRequestMethod("POST");
                    conn.setDoInput(true);
                    conn.setDoOutput(true);
                    OutputStream os = conn.getOutputStream();

                    os.close();

                    int responseCode=conn.getResponseCode();

                    if (responseCode == HttpsURLConnection.HTTP_OK) {

                        BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        StringBuilder sb = new StringBuilder("");
                        String line="";
                        while ((line = in.readLine()) != null)
                        {
                            sb.append(line).append("\n");
                        }
                        result = sb.toString();
                    }

                    assert inputStream != null;
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line).append("\n");
                    }
                    result = sb.toString();
                } catch (Exception e) {
                    Log.i("tagconvertstr", "["+result+"]");
                    System.out.println(e);
                }
                finally {
                    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
                }
                return result;
            }

            @Override
            protected void onPostExecute(String result){

                myJSON = result;
                showList();

            }
        }
        GetDataJSON g = new GetDataJSON();
        g.execute();
    }



    protected void showList(){
        try {
            peoples = new JSONArray(myJSON);
            for(int i=0;i<peoples.length();i++){

                JSONObject c = peoples.getJSONObject(i);
                String name = c.getString(TAG_NAME);

                HashMap<String,String> persons = new HashMap<String,String>();

                persons.put(TAG_NAME,name);

                personList.add(persons);
            }



            ListAdapter adapter = new SimpleAdapter(
                    ListViewMultipleSelectionActivity.this, personList, R.layout.result,
                    new String[]{TAG_NAME},
                    new int[]{R.id.name}
            );




            list1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
            list1.setAdapter(adapter);

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }



}

main.xml中

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

    <Button
        android:id="@+id/testbutton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="Submit" />

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@id/testbutton"
        android:layout_alignParentTop="true"/>

</RelativeLayout>

为result.xml

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

<CheckBox
    android:id="@+id/cbBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical" >
</CheckBox>

<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dp"
    android:orientation="vertical"
    android:layout_weight="1" >

    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:textStyle="bold"/>

</LinearLayout>

</LinearLayout>

我已经在testbutton(Button)上实现了这一点,请点击

button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                SparseBooleanArray checked = list1.getCheckedItemPositions();
                ArrayList<String> selectedItems = new ArrayList<String>();
                for (int i = 0; i < checked.size(); i++) {
                    int position = checked.keyAt(i);
                       if (checked.valueAt(i))
                         selectedItems.add((String) adapter.getItem(position));
                }

                String[] valuess = new String[selectedItems.size()];

                for (int i = 0; i < selectedItems.size(); i++) {
                    valuess[i] = selectedItems.get(i);
                }
                Toast.makeText(ListViewMultipleSelectionActivity.this, String.valueOf(valuess), Toast.LENGTH_SHORT).show();
            }
        });

这是我点击后的

E/-->>>>: [Ljava.lang.String;@ca01299

3 个答案:

答案 0 :(得分:1)

您可以做的是创建一个自定义类来存储这些值以及支持它的自定义适配器。因此,每当您单击该按钮时,您都可以调用给定的函数来检索这些项的状态。示例架构如下:

PS:由于我不知道你想要对选中的值做什么,我给你留下了你可以根据需要改变的评论。

<强> MainActivity.java

package com.rencsaridogan.stackoverflow;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

  ArrayList<ExampleClass> objects;

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

    objects = new ArrayList<>();

    for (int i = 0; i < 10; i++){
      objects.add(new ExampleClass("Example Name " + i));
    }

    final ListView listView = (ListView) findViewById(R.id.listView);
    final Button testButton = (Button) findViewById(R.id.testButton);
    final ExampleAdapter exampleAdapter = new ExampleAdapter(this, R.layout.list_cell, objects);
    listView.setAdapter(exampleAdapter);
    exampleAdapter.notifyDataSetChanged();

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

  }

  private void getCheckedItems(){
    for (int i = 0; i < 10; i++) {
      if (objects.get(i).isChecked()){
        Log.i("MainActivity",i + " is checked");
        /**
         * Value is checked, do what you need to do here
         */
      } else {
        Log.i("MainActivity",i + " is NOT checked");
        /**
         * Value is NOT checked
         */
      }
    }
  }
}

<强> ExampleAdapter.java

package com.rencsaridogan.stackoverflow;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import java.util.ArrayList;
/**
 * Created by rencsaridogan on 16/02/2017.
 */

public class ExampleAdapter extends ArrayAdapter<ExampleClass> {

  ArrayList<ExampleClass> objects;
  Listener listener;
  Context context;

  public ExampleAdapter(Context context, int resource, ArrayList<ExampleClass> objects) {
    super(context, resource);
    this.context = context;
    this.objects = objects;
  }

  @Override public int getViewTypeCount() {
    return super.getViewTypeCount();
  }

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

  @SuppressLint("InflateParams") @Override public View getView(int position, View convertView, @NonNull ViewGroup parent) {

    if (convertView == null){
      Log.i("ExampleAdapter","ConvertView inflated");
      convertView = LayoutInflater.from(context).inflate(R.layout.list_cell, null, false);
    }

    Log.i("ExampleAdapter","Setting of values");

    final ExampleClass data = objects.get(position);
    final ViewHolder viewHolder = new ViewHolder();

    viewHolder.textView = (TextView) convertView.findViewById(R.id.textView);
    viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);

    viewHolder.textView.setText(data.getName());

    viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        data.setChecked(isChecked);
      }
    });

    return convertView;
  }

  public void setListener(Listener listener) {
    this.listener = listener;
  }

  private class ViewHolder {

    TextView textView;
    CheckBox checkBox;
  }

  public ArrayList<ExampleClass> getObjects() {
    return objects;
  }

  public void setObjects(ArrayList<ExampleClass> objects) {
    this.objects = objects;
    notifyDataSetChanged();
  }

  @Override public long getItemId(int position) {
    return super.getItemId(position);
  }

  public interface Listener {
    void onCheckedChanged(int position);
  }
}

<强> ExampleClass.java

package com.rencsaridogan.stackoverflow;

/**
 * Created by rencsaridogan on 16/02/2017.
 */

public class ExampleClass {
  String name;
  boolean isChecked;

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

  public ExampleClass(String name, boolean isChecked) {
    this.name = name;
    this.isChecked = isChecked;
  }

  public String getName() {
    return name;
  }

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

  public boolean isChecked() {
    return isChecked;
  }

  public void setChecked(boolean checked) {
    isChecked = checked;
  }
}

答案 1 :(得分:0)

  1. 将复选框对象设置为行视图的标记,可能是适配器的getView()方法中的“convertView”。

  2. 在行视图上单击侦听器。 3.在点击监听器中,从onClick方法中查看该参数的行查看getTag并将其强制转换为复选框,然后将该复选框对象的setChecked设置为true。

  3. 代码可能如下所示,

      convertView.setTag(yourCheckBoxObject);
        convertView.setOnClickListener(new OnClickListener() {
    
            @Override
            public void onClick(View v) {
                CheckBox cb = (CheckBox) v.getTag();
                cb.setChecked(true);
            }
        });
    

    请参阅此观点以获取更多信息Getting an issue while checking the dynamically generated checkbox through list view

答案 2 :(得分:0)

在你的适配器中有一个名为getView()的@override方法,你将获得你将点击的当前项目

  holder.checkbox.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // TODO Auto-generated method stub

    CheckBox checkBox=(CheckBox) view;
      String tagName="";
     if(checkBox.isChecked()){
       tagName=checkBox.getTag().toString();
       deleteServices.add(tagName);
       checkboxArrayList.add(checkBox);
    }else {
           checkboxArrayList.remove(checkBox);
           tagName=checkBox.getTag().toString();
                if(deleteServices.size()>0&&deleteServices.contains(tagName)){

deleteServices.remove(标签名);     }

        });