共享首选项不适用于存储所选的复选框

时间:2016-05-17 08:33:04

标签: android listview android-fragments checkbox android-sharedpreferences

当我选中带有复选框的列表视图中的复选框时,在我更改列表视图后单击另一个选项卡,如果我回到上一个选项卡,选中之前的复选框,现在不会被选中....所以,我怎么能在我更改选项卡时以及在我回到上一个选项卡后检查维护复选框?谢谢!

这是我的代码......

ADAPTER:

        public abstract class PlanetAdapter extends ArrayAdapter<Planet> implements CompoundButton.OnCheckedChangeListener

        {

            private List<Planet> planetList=null;
            private Context context=null;
            ArrayList<Birra> objects;
            private HashMap<Integer, Planet> pizzaSelected = new HashMap<>();
            public boolean Checked;

            public  PlanetAdapter(List<Planet> planetList, Context context) {

                super(context, R.layout.single_listview_item, planetList);
                this.planetList = planetList;
                this.context = context;
            }


            public  class PlanetHolder  {
                public TextView planetName;
                public TextView distView;
                public TextView valuta;
                public CheckBox chkBox;
                public EditText edit;
                //public String quantità;
                public boolean checked;
                public TextView id;
            }
            @Override
            public int getCount() {
                return planetList.size();
            }

            @Override
            public Planet getItem(int position) {
                return planetList.get(position);
            }

            @Override
            public long getItemId(int position) {
                return planetList.get(position).getId();
            }


            @Override
            public View getView(final int position, View convertView, ViewGroup parent) {

                View row = convertView;
                PlanetHolder holder = null;

                if (row == null) {
                    LayoutInflater inflater = ((Activity) context).getLayoutInflater();
                    row = inflater.inflate(R.layout.single_listview_item, parent, false);
                    holder = new PlanetHolder();
                    holder.planetName = (TextView) row.findViewById(R.id.name);
                    holder.distView = (TextView) row.findViewById(R.id.dist);
                    holder.valuta = (TextView) row.findViewById(R.id.valuta);
                    holder.chkBox = (CheckBox) row.findViewById(R.id.chk_box);
                    holder.edit = (EditText) row.findViewById(R.id.editText);
                    holder.edit.setVisibility(View.GONE);
                    holder.edit.setEnabled(false);
                    holder.id = (TextView) row.findViewById(R.id.id);


                    row.setTag(holder);

                } else {
                    holder = (PlanetHolder) row.getTag();
                }
                final Planet p = planetList.get(position);
                SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                boolean isChecked = states.getBoolean("holder.chkBox"+holder.planetName.getText().toString(), false);
                System.out.println(isChecked);
                if(isChecked) {
                    holder.chkBox.setChecked(true);
                } else {
                    holder.chkBox.setChecked(false);
                }

     final PlanetHolder finalHolder = holder;




            holder.chkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (finalHolder.chkBox.isChecked()) {
                        finalHolder.edit.setVisibility(View.VISIBLE);
                        finalHolder.edit.setEnabled(true);
                        SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = states.edit();
                        editor.putBoolean("holder.chkBox"+finalHolder.planetName.getText().toString(), true);



                    } else {
                        SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = states.edit();
                        finalHolder.edit.setVisibility(View.GONE);
                        finalHolder.edit.setEnabled(false);
                        finalHolder.edit.setText("");
                        editor.putBoolean("holder.chkBox" , false);

                    }
                    SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = states.edit();
                    editor.commit();
                    System.out.println(editor.commit());
                }
            });

     finalHolder.edit.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    p.setQuantità(finalHolder.edit.getText().toString().trim());


                }
            });


                    holder.planetName.setText(p.getName());
                    holder.distView.setText("" + p.getDistance());
                    holder.valuta.setText("" + p.getValuta());
                    holder.chkBox.setChecked(p.isSelected());
                    holder.chkBox.setTag(p);
                    holder.edit.setEnabled(false);
                  //  holder.id.setId(p.getId());


            return row;
                }

                ArrayList<Planet> getBox() {
                    ArrayList<Planet> box = new ArrayList<Planet>();
                    for (Planet p : planetList) {
                        if (p.selected)
                            box.add(p);
                    }
                    return box;
                }

            }

FRAGMENT:

    public class MyListFragment extends Fragment implements
            android.widget.CompoundButton.OnCheckedChangeListener {

        ListView lv;
        ArrayList<Planet> planetList;
        PlanetAdapter plAdapter;
        BirraAdapter biAdapter;
        PlanetAdapter.PlanetHolder holder;




        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment

            ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_list2, container, false);

            Button mButton = (Button) rootView.findViewById(R.id.button);
            mButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    showResult(v);


                }
            });
            //return inflater.inflate(R.layout.fragment_list2, container, false);
            return rootView;
        }


        @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);


            lv = (ListView)getView().findViewById(R.id.listview);
            displayPlanetList();


        }


        private void displayPlanetList() {

            planetList = new ArrayList<Planet>();
            planetList.add(new Planet("Margherita", 6, "€",1));
            planetList.add(new Planet("Diavola", 7,"€",2));
            planetList.add(new Planet("Bufalina", 5,"€",3));
            planetList.add(new Planet("Marinara", 5, "€",4));
            planetList.add(new Planet("Viennese", 4, "€",5));

            plAdapter = new PlanetAdapter(planetList, getContext()) {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                    int pos = lv.getPositionForView(buttonView);
                    if (pos != ListView.INVALID_POSITION) {
                        Planet p = planetList.get(pos);
                        p.setSelected(isChecked);


                /*Toast.makeText(
                    getActivity(),
                    "Clicked on Pizza: " + p.getName() + ". State: is "
                            + isChecked, Toast.LENGTH_SHORT).show();*/
                    }


                }
            };

            lv.setAdapter(plAdapter);
            //plAdapter.notifyDataSetChanged();
        }



        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            /*int pos = lv.getPositionForView(buttonView);
            if (pos != ListView.INVALID_POSITION) {
                Planet p = planetList.get(pos);
                p.setSelected(isChecked);


                *//*Toast.makeText(
                    getActivity(),
                    "Clicked on Planet: " + p.getName() + ". State: is "
                            + isChecked, Toast.LENGTH_SHORT).show();*//*
            }*/

        }


        public void showResult(View v) {
            String  result2 = "Selected Product are :";
            int totalAmount2=0;

            String a="";
            for (Birra b : biAdapter.getBox()){

                if (b.selected){

                    result2 += "\n" + b.name+" "+b.distance+"€"+"q.tà :"+b.getQuantità();
                    int quantitaInt= Integer.parseInt(b.getQuantità());
                    totalAmount2+=b.distance * quantitaInt;
                    //a=String.valueOf(totalAmount);


                }
            }
        /*  for (Planet p : plAdapter.getBox()) {
                if (p.selected){

                    result += "\n" + p.name+" "+p.distance+"€"+"q.tà :"+p.getQuantità();
                    int quantitaInt= Integer.parseInt(p.getQuantità() );
                    totalAmount+=p.distance * quantitaInt;
                    //a=String.valueOf(totalAmount);


                }
            }*/
          //Toast.makeText(getActivity(), result + "\n" + "Total Amount:=" + totalAmount + "€", Toast.LENGTH_LONG).show();
            Toast.makeText(getActivity(), result2 + "\n" + "Total Amount:=" + totalAmount2 + "€", Toast.LENGTH_LONG).show();

            /*Bundle bun2 = new Bundle();
            bun2.putString("scelta", result);
            TwoFragment fgsearch2 = new TwoFragment();
            fgsearch2.setArguments(bun2);
            android.support.v4.app.FragmentTransaction transaction2 = getActivity().getSupportFragmentManager().beginTransaction();
            transaction2.replace(R.id.content_main, fgsearch2);
            transaction2.commit();


            Bundle bun = new Bundle();
            bun.putString("totale", a);
            TwoFragment fgsearch = new TwoFragment();
            fgsearch.setArguments(bun);
            android.support.v4.app.FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.content_main2, fgsearch);
            transaction.commit();
    */

MAIN:

MAIN:

public class Main extends AppCompatActivity{



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

        getSupportFragmentManager().beginTransaction().

                replace(R.id.fragmentContainer, new MyListFragment()).commit();



    }


    @Override protected void onDestroy() {
        SharedPreferences preferences=getSharedPreferences("states", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=preferences.edit();
        editor.clear().apply();
        super.onDestroy();
    }

}









        }

3 个答案:

答案 0 :(得分:0)

只需更改 OnCheckedChangeListener 代码,如下所示。你没有在改变后做出承诺:

 holder.chkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (finalHolder.chkBox.isChecked()) {
                finalHolder.edit.setVisibility(View.VISIBLE);
                finalHolder.edit.setEnabled(true);
                SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = states.edit();
                editor.putBoolean("holder.chkBox"+finalHolder.planetName.getText().toString(), true);
                editor.commit();


            } else {
                SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = states.edit();
                finalHolder.edit.setVisibility(View.GONE);
                finalHolder.edit.setEnabled(false);
                finalHolder.edit.setText("");
                editor.putBoolean("holder.chkBox"+finalHolder.planetName.getText().toString() , false);
                editor.commit();
            }
        }
    });

这会奏效。 :)

答案 1 :(得分:0)

您正在重新初始化SharedPreferences状态,它应该在进入getView之前完成一次。你可以在PlanetAdapter的构造函数中做到这一点。

答案 2 :(得分:0)

在你的getView()中,我认为你应该调用apply()而不是commit来将值保存到sharedPreferences;立即申请保存。此外,在将shared.planetName用作sharedPreferences中的键之前,应将其设置为holder.planetName。

检查出来:

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    View row = convertView;
    PlanetHolder holder = null;

    if (row == null) {
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        row = inflater.inflate(R.layout.single_listview_item, parent, false);
        holder = new PlanetHolder();
        holder.planetName = (TextView) row.findViewById(R.id.name);
        holder.distView = (TextView) row.findViewById(R.id.dist);
        holder.valuta = (TextView) row.findViewById(R.id.valuta);
        holder.chkBox = (CheckBox) row.findViewById(R.id.chk_box);
        holder.edit = (EditText) row.findViewById(R.id.editText);
        holder.edit.setVisibility(View.GONE);
        holder.edit.setEnabled(false);
        holder.id = (TextView) row.findViewById(R.id.id);


        row.setTag(holder);

    } else {
        holder = (PlanetHolder) row.getTag();
    }

    final Planet p = planetList.get(position);
    // I think you should set a value to holder.planetName before using the value as
    // preference key
    holder.planetName.setText(p.getName());
    holder.distView.setText("" + p.getDistance());
    holder.valuta.setText("" + p.getValuta());
    holder.chkBox.setChecked(p.isSelected());
    holder.chkBox.setTag(p);
    holder.edit.setEnabled(false);
    //  holder.id.setId(p.getId());

    SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
    boolean isChecked = states.getBoolean("holder.chkBox"+holder.planetName.getText().toString(), false);
    System.out.println(isChecked);
    if(isChecked) {
        holder.chkBox.setChecked(true);
    } else {
        holder.chkBox.setChecked(false);
    }

    final PlanetHolder finalHolder = holder;




    holder.chkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (finalHolder.chkBox.isChecked()) {
                finalHolder.edit.setVisibility(View.VISIBLE);
                finalHolder.edit.setEnabled(true);
                SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = states.edit();
                editor.putBoolean("holder.chkBox"+finalHolder.planetName.getText().toString()
                        , true);



            } else {
                SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = states.edit();
                finalHolder.edit.setVisibility(View.GONE);
                finalHolder.edit.setEnabled(false);
                finalHolder.edit.setText("");
                editor.putBoolean("holder.chkBox" , false);

            }
            SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = states.edit();
            editor.apply();
            System.out.println(editor.commit());
        }
    });

    finalHolder.edit.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            p.setQuantità(finalHolder.edit.getText().toString().trim());


        }
    });




    return row;
}