Save status of a Checkbox

Asked

Viewed 659 times

3

I need to save the status of my Checkbox, they’re inside a Spinner, and every time I open Spinner he cleans the Checkbox.

Admlistagem.java

        final String[] select_qualification = {
                "Todos", "1", "2", "3", "4",
                "5", "6"};
        Spinner spinner = (Spinner) findViewById(R.id.spinner);

        ArrayList<StateVO> listVOs = new ArrayList<>();

        for (int i = 0; i < select_qualification.length; i++) {
            StateVO stateVO = new StateVO();
            stateVO.setTitle(select_qualification[i]);
            stateVO.setSelected(false);
            listVOs.add(stateVO);
        }
        MyAdapter myAdapter = new MyAdapter(AdmListagem.this, 0,
                listVOs);
        spinner.setAdapter(myAdapter);

spinner_item2.xml

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

    <TextView
        android:id="@+id/text"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="25dp"
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp"
        android:textSize="16dp"
        android:textColor="#000000"
        android:background="@drawable/spinner_item_border" />

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

Myadapter.java

public class MyAdapter extends ArrayAdapter<StateVO>  {
    private Context mContext;
    private ArrayList<StateVO> listState;
    private MyAdapter myAdapter;
    private boolean isFromView = false;
    String[] values;
    Boolean[] checkedStatus;

    public MyAdapter(Context context, int resource, List<StateVO> objects) {
        super(context, resource, objects);
        this.mContext = context;
        this.listState = (ArrayList<StateVO>) objects;
        this.myAdapter = this;
    }

    @Override
    public View getDropDownView(int position, View convertView,
                                ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    public View getCustomView(final int position, View convertView,
                              ViewGroup parent) {

        final ViewHolder holder;
        if (convertView == null) {
            LayoutInflater layoutInflator = LayoutInflater.from(mContext);
            convertView = layoutInflator.inflate(R.layout.spinner_item2, null);
            holder = new ViewHolder();
            holder.mTextView = (TextView) convertView
                    .findViewById(R.id.text);
            holder.mCheckBox = (CheckBox) convertView
                    .findViewById(R.id.checkbox);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.mTextView.setText(listState.get(position).getTitle());

        // To check weather checked event fire from getview() or user input
        isFromView = true;
        holder.mCheckBox.setChecked(listState.get(position).isSelected());
        isFromView = false;

        if ((position == 0)) {
            holder.mCheckBox.setVisibility(View.INVISIBLE);
        } else {
            holder.mCheckBox.setVisibility(View.VISIBLE);
        }
        holder.mCheckBox.setTag(position);
        holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int getPosition = (Integer) buttonView.getTag();
                String t = String.valueOf(getPosition);
                Toast.makeText(mContext, t, Toast.LENGTH_SHORT).show();

            }
        });
        return convertView;
    }

    private class ViewHolder {
        private TextView mTextView;
        private CheckBox mCheckBox;
    }
}

Statevo.java

public class StateVO {
    private String title;
    private boolean selected;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }
}

When running the application and Spinner choose the items, and click on the screen, and open Spinner again it is without any markup in the Checkbox

  • Use Estatic variables for this or sharedpreferences, it can also help you save the value

  • @Matheus Could you give me a hand showing me how it would look ?

  • So... is that it is a process a little laborious, in your case you will have to access the children of your spinner, and see which child is the checkbox, then when it is clicked on the button to check, save in a variable environment that would be the Sharedpreferences...

  • @Matheus, Oh yes, so I’ll try to use that you said

1 answer

2


I suppose the reason of the field selected of the Statevo class.

In the Adapter use it to save and recover Checkbox status.

The recover part you already did. Missing the save part, which should be done in the onCheckedChanged()

public View getCustomView(final int position, View convertView,
                          ViewGroup parent) {

    ...
    ...
    // To check weather checked event fire from getview() or user input
    isFromView = true;
    holder.mCheckBox.setChecked(listState.get(position).isSelected());
    isFromView = false;

    //holder.mCheckBox.setTag(position);
    holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isFromView)return;

            //int getPosition = (Integer) buttonView.getTag();
            String t = String.valueOf(position);
            Toast.makeText(mContext, t, Toast.LENGTH_SHORT).show();

            //Guarda o estado do CheckBox
            listState.get(position).setSelected(isChecked);

        }
    });
    return convertView;
}

Notes:

  • No need to store item position in the tagcheckbox.
    Since positionbe declared as final it is possible to use it within the method onCheckedChanged().
  • I used the flag isFromView so that the method onCheckedChanged() return immediately so that Toast is displayed only when the user clicks the Checkbox.
  • If you don’t want to make use of flag and continue to use tag, in order to obtain the correct position in the method onCheckedChanged(), shall receive the position value before the line holder.mCheckBox.setChecked(listState.get(position).isSelected());
  • I tried to do so, but sometimes it does not save and when saves it shuffles the checkbox that are selected, for example by checking the last two, when I open ta a 2 and 3.

  • I don’t see why. He also changes the text?

  • No, he does not change the position of the texts, I had tried before but I forgot to mention in the question.

  • I always do it and it works. The only difference is that I don’t use the tag to hold position, use position directly. However, I do not see this as a problem.

  • Our stranger then, I must have done something wrong, but where I do not know

  • I think I figured out the problem: by doing holder.mCheckBox.setChecked(listState.get(position).isSelected());before "set" the tag the position obtained by getTag() in the onCheckedChanged() wrong position. 3 ways to solve: 1 - use flag isFromView; 2 - "set a tag before; 3 - use position instead of getTag(). I’ll change the answer.

  • Could you edit the question showing me how to change it here ? If yes thank you very much.

  • I already include in the answer the changes you should make in the code. The question should not be edited otherwise the answers are meaningless.

  • I ended up missing what I said I should have said "Edit your answer"

  • Can you understand the changes I made? I just commented a few lines, I used positioninstead of getPosition, added if(isFromView)return; and listState.get(position).setSelected(isChecked);

  • Thank you very much, I understood yes the amendments helped me a lot and thanks for the expensive attention

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.