如何使用共享首选项保存CheckBox的状态?

时间:2016-05-07 12:35:02

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

我有标签和查看带有列表视图的寻呼机复选框,但是如果我选择一个复选框并且我更改标签,并且在我点击上一个标签后,之前选中的复选框,现在不会被检查。为什么?

enter image description here

FRAGMENT:

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

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        SharedPreferences preferences = getContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);


boolean value = preferences.getBoolean("showActivity", true);
        String value2 = preferences.getString("KEY", String.valueOf(true));
        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, "€"));
        planetList.add(new Planet("Diavola", 7,"€"));
        planetList.add(new Planet("Bufalina", 5,"€"));
        planetList.add(new Planet("Marinara", 5,"€"));
        planetList.add(new Planet("Viennese", 4,"€"));

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

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

    }
    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();
*/
    }
}

ADAPTER:

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

{

  private List<Planet> planetList;
  private Context context;
  ArrayList<Birra> objects;


  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à;
 } 
  @Override
  public View getView(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);
          row.setTag(holder);
      } else {
          holder = (PlanetHolder) row.getTag();
      }
       final Planet p = planetList.get(position);

      holder.chkBox.setOnCheckedChangeListener(PlanetAdapter.this);
      final PlanetHolder finalHolder = holder;
      holder.chkBox.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              if (finalHolder.chkBox.isChecked()) {
                  finalHolder.edit.setVisibility(View.VISIBLE);
                  finalHolder.edit.setEnabled(true);
                  SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
                  SharedPreferences.Editor editor = sharedPreferences.edit();
                  editor.putBoolean("showActivity", finalHolder.chkBox.isChecked());
                  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());
                          SharedPreferences preferences = getContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
                          SharedPreferences.Editor editor = preferences.edit();
                          editor.putString("KEY", finalHolder.edit.getText().toString());
                          //editor.putBoolean("chkBox", true);
                          editor.commit();
                          }
                  });
              } else {
                  finalHolder.edit.setVisibility(View.GONE);
                  finalHolder.edit.setEnabled(false);
                  finalHolder.edit.setText(null);
              }
          }
      });
      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);

      return row;
  }

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


}

2 个答案:

答案 0 :(得分:0)

这是因为您的复选框未保存点击结果。简单地使用SharedPreference来存储数据。

喜欢:

  public class UserPreference {


        SharedPreferences pref;

  // Editor for Shared preferences
  SharedPreferences.Editor editor;

  // Context
  Context _context;

  // Shared pref mode
  int PRIVATE_MODE = 0;

  // Sharedpref file name
  private static final String PREF_NAME = "user_preference";

  public static final String isSportsCheck = "isSportsChecked";
  public static final String isTechnologyCheck = "isTechnologyChecked";

   public UserPreference(Context context){
      this._context = context;
      pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
      editor = pref.edit();
  }

  public void createWork(boolean sports, boolean tech){
      editor.putBoolean(isSportsCheck, sports);
      editor.putBoolean(isTechnologyCheck, tech);
      editor.commit();
  }

  public HashMap<String, String> getWorkDetails(){
      HashMap<String, String> user = new HashMap<String, String>();
      user.put(isSportsCheck, pref.getBoolean(isSportsCheck, false));
      user.put(isTechnologyCheck, pref.getBoolean(isTechnologyCheck, false));

      return user;
  }

在这里,你可以改变运动,技术,你想要的任何价值,如Bufalina,Marinara。用法:

UserPreference u = new UserPreference(getContext());
u.createWork(true, true);

答案 1 :(得分:0)

一个简单而优雅的解决方案是在android中使用一个非常简单的库TinyDB,这只不过是对共享首选项的抽象。

您可以在活动的onCreate()方法中对其进行初始化,如下所示:

TinyDB tinydb = new TinyDB(this);
And then use it like this:

tinydb.putString("userName", "john");
String currentUser = tinydb.getString("userName");

希望它有所帮助。