简体   繁体   中英

Listview items with checkbox checked at start

I have a fragment with a listView.

The view is populated from a remote received JSON array as follows:

private void callVolley(){



        SharedPreferences prefs3 =
                getActivity().getSharedPreferences(MIEXAMEN, Context.MODE_PRIVATE);

        final String id_materia= "42";
        final String num_examen= "787878";
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Cargando temas de la materia seleccionada...");
        showDialog();


        JsonArrayRequest jArr = new JsonArrayRequest(url+"?id="+id_materia, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                Log.d(TAG, response.toString());
                hideDialog();




                // Parsing json
                for (int i = 0; i < response.length(); i++) {
                    try {
                        JSONObject obj = response.getJSONObject(i);

                        Data item = new Data();

                        item.setMenu(obj.getString(TAG_NOMBRE));
                        item.setId(obj.getString(TAG_ID));


                        itemList.add(item);



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

                // list.invalidateViews();
                adapter.notifyDataSetChanged();



            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hideDialog();
            }
        });


        AppController.getInstance().addToRequestQueue(jArr);
    }

Then I add programmatically a checkbox to each list item. This is the adapter:

 public class Adapter extends BaseAdapter {

    private Context activity;
    private ArrayList<Data> data;
    private static LayoutInflater inflater = null;
    private View vi;
    private ViewHolder viewHolder;

    public Adapter(Context context, ArrayList<Data> items) {
        this.activity = context;
        this.data = items;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

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

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

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        vi = view;
        final int pos = position;
        Data items = data.get(pos);

        if(view == null) {
            vi = inflater.inflate(R.layout.list_row, null);
            viewHolder = new ViewHolder();
            viewHolder.checkBox = (CheckBox) vi.findViewById(R.id.cb);
            viewHolder.menu = (TextView) vi.findViewById(R.id.nama_menu);
            vi.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolder) view.getTag();

        }
        viewHolder.menu.setText(items.getMenu());
        if(items.isCheckbox()){
            viewHolder.checkBox.setChecked(true);
        } else {
            viewHolder.checkBox.setChecked(false);
        }

        return vi;
    }

    public ArrayList<Data> getAllData(){
        return data;
    }

    public void setCheckBox(int position){
        Data items = data.get(position);
        items.setCheckbox(!items.isCheckbox());
        notifyDataSetChanged();
    }

    public class ViewHolder{
        TextView menu;
        CheckBox checkBox;
    }
}

At start I need all checkboxes to be checked.

Then the user can check/uncheck the desired items.

On the fragment there is a button that reads all items checkbox states.

What should I implement to put all items in status checked so that on button clicked all items are recognized as checked?

This is a screenshot at start with all items unchecked: 在此处输入图片说明

EDIT

Code for the button onClickListener in the fragment:

 fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkbox = "";
                checkbox_id = "";

                for (Data hold : adapter.getAllData()) {
                    if (hold.isCheckbox()) {
                        checkbox += "\n" + hold.getMenu();
                        checkbox_id +=  hold.getId()+",";


                    }
                }
                if (!checkbox.isEmpty()) {
                    dipilih = checkbox;
                    String preguntas = checkbox_id;
                    mPref = getActivity().getSharedPreferences(MIEXAMEN, Context.MODE_PRIVATE);


                    SharedPreferences.Editor editor = mPref.edit();




                    editor.putString("preguntas_numero_string",preguntas);
                    editor.putString("preguntas_string",dipilih);

                    Log.d("seleccion","seleccion preguntas "+preguntas);
                    Log.d("seleccion","seleccion dipilih "+dipilih);

                    editor.apply();




                } else {
                    dipilih = "No has seleccionado ningún tema.";
                }

                formSubmit(dipilih);
            }
        });

Do the following changes:

When you are adding Data to the list of Data.

                    Data item = new Data();

                    item.setMenu(obj.getString(TAG_NOMBRE));
                    item.setId(obj.getString(TAG_ID));
                    item.setCheckbox(true)

                    itemList.add(item);

This will initially make the checkbox checked.

Edit:

Update your xml layout. in your CheckBox put this attribute.

android:clickable="false"

Update your list setOnItemClickListener

    list.setOnItemClickListener(new OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            adapter.setCheckBox(position);
          }
    });

Try replacing with the below code

viewHolder.checkBox.setChecked(true);

instead of

if(items.isCheckbox()){
            viewHolder.checkBox.setChecked(true);
        } else {
            viewHolder.checkBox.setChecked(false);
        }

Use this. It should work. -

Initially this -

viewHolder.checkBox.setChecked(true);

Then

  viewHolder.checkBox.setOnCheckedChangeListener(new 
  CompoundButton.OnCheckedChangeListener() {

    @Override
   public void onCheckedChanged(CompoundButton 
     buttonView,boolean isChecked) {
   if(isChecked){
           viewHolder.checkBox.setChecked(true);
       } else {
           viewHolder.checkBox.setChecked(false);
       }
   }

} );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM