如何使用共享首选项

时间:2018-05-07 15:46:42

标签: android checkbox android-recyclerview sharedpreferences

我有一个回收站视图,在回收站视图的行内,我有一个带有5个复选框的文本。 我的问题是,每当我选中一个复选框时,共享偏好保存在同一位置的所有复选框。

(编辑)示例:我选中第一行的复选框#2,然后检查其他行的所有其他复选框#2。我回到片段后。

以下是我的适配器代码

public class HabitosAdapter extends RecyclerView.Adapter<HabitosAdapter.MyViewHolder> {
    private List<Habitos> mHabitosList;
    private Fragment mFragment;
    private Context mContext;
    private CheckBox[] checkBoxes = new CheckBox[5];



    public class MyViewHolder extends RecyclerView.ViewHolder{
        TextView nombre;
        CardView habitosCardView;
        CheckBox CB1, CB2, CB3, CB4, CB5 ;

        public MyViewHolder(View itemView) {
            super(itemView);
            nombre = (TextView) itemView.findViewById(R.id.nombreHabito);
            habitosCardView = itemView.findViewById(R.id.habitos_card_view);
           CB1 = (CheckBox) itemView.findViewById(R.id.CBdia1);
            CB2 = (CheckBox) itemView.findViewById(R.id.CBdia2);
            CB3 = (CheckBox) itemView.findViewById(R.id.CBdia3);
            CB4 = (CheckBox) itemView.findViewById(R.id.CBdia4);
            CB5 = (CheckBox) itemView.findViewById(R.id.CBdia5);
        }
    }

    public HabitosAdapter(Context mContext, List<Habitos> habitosList){
        this.mContext = mContext;
        this.mHabitosList = habitosList;
    }

    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.habitos_list_row, parent, false);
        SharedPreferences preferences = mContext.getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
        boolean valueBoolean = preferences.getBoolean("KEY", false);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("KEY", valueBoolean);
        editor.commit();


        return new MyViewHolder(itemView);

    }
      public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position){

        holder.nombre.setText(mHabitosList.get(position).getNombre());

        holder.CB1.setChecked(getFromSP("CB1"));
       holder.CB1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                saveInSp("CB1", b);
            }
        });
        holder.CB2.setChecked(getFromSP("CB2"));
        holder.CB2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                if(holder.CB2.isChecked()){
                    saveInSp("CB2", true);
                } else{
                    saveInSp("CB2", false);
                }
            }
        });
        holder.CB3.setChecked(getFromSP("CB3"));
        holder.CB3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                saveInSp("CB3", b);
            }
        });
        holder.CB4.setChecked(getFromSP("CB4"));
        holder.CB4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                saveInSp("CB4", b);
            }
        });
        holder.CB5.setChecked(getFromSP("CB5"));
        holder.CB5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                saveInSp("CB5",b);
            }
        });
     }
    public int getItemCount(){
        return mHabitosList.size();
    }
    private boolean getFromSP(String key) {
        SharedPreferences preferences = mContext.getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
        return preferences.getBoolean(key, false);
    }

    private void saveInSp(String key,boolean value){
        SharedPreferences preferences = mContext.getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(key, value);
        editor.commit();
    }


}

如何只保存已选中的复选框? 我知道我必须得到已检查的特定CheckBox而不是在所有CheckBoxes2上设置监听器,但我不知道如何做到这一点,我正在开发我的第一个应用程序,所以感谢您的耐心。

2 个答案:

答案 0 :(得分:0)

已编辑至最终答案

public class MainActivity extends AppCompatActivity {


CheckBox CB1, CB2, CB3, CB4, CB5 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    EditText courseTitleEditText = null;
    CB1 = (CheckBox) findViewById(R.id.CBdia1);
    CB2 = (CheckBox) findViewById(R.id.CBdia2);
    CB3 = (CheckBox) findViewById(R.id.CBdia3);
    CB4 = (CheckBox) findViewById(R.id.CBdia4);
    CB5 = (CheckBox) findViewById(R.id.CBdia5);


    SharedPreferences preferences = getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
    boolean valueBoolean = preferences.getBoolean("KEY", false);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putBoolean("KEY", valueBoolean);
    editor.commit();


    CB1.setChecked(getFromSP("CB1"+position));
    CB1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            saveInSp("CB1"+position, b);
        }
    });
    CB2.setChecked(getFromSP("CB2"+position));
    CB2.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            if(CB2.isChecked()){
                saveInSp("CB2"+position, true);
            } else{
                saveInSp("CB2"+position, false);
            }
        }
    });
    CB3.setChecked(getFromSP("CB3"+position));
    CB3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            saveInSp("CB3"+position, b);
        }
    });
    CB4.setChecked(getFromSP("CB4"+position));
    CB4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            saveInSp("CB4"+position, b);
        }
    });
    CB5.setChecked(getFromSP("CB5"+position));
    CB5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            saveInSp("CB5"+position,b);
        }
    });

}

private boolean getFromSP(String key) {
    SharedPreferences preferences = getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
    return preferences.getBoolean(key, false);
}

private void saveInSp(String key,boolean value){
    SharedPreferences preferences = getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putBoolean(key, value);
    editor.commit();
}

}

答案 1 :(得分:0)

public class FireInfoAdapter extends RecyclerView.Adapter<FireInfoAdapter.FireInfoViewHolder> {
    private List<ResidentialFireBaseInfo> items = new ArrayList<>();
    private onItemClickListener listener;
    private boolean isMyValueChecked;


    public FireInfoAdapter(List<ResidentialFireBaseInfo> items, onItemClickListener listener) {
        this.items = items;
        this.listener = listener;
    }

    @NonNull
    @Override
    public FireInfoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_fire_base_info, parent, false);
        SharedPreferences sharedPreferences = view.getContext().getSharedPreferences("My preference", Context.MODE_PRIVATE);
        isMyValueChecked = sharedPreferences.getBoolean("checkbox", false);
        return new FireInfoViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull FireInfoViewHolder holder, int position) {
        holder.bind(items.get(position));
        holder.itemCheckbox.setOnClickListener(view -> {
                    SharedPreferences sharedPreferences = view.getContext().getSharedPreferences("My preference", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putBoolean("checkbox", holder.itemCheckbox.isChecked());
                    editor.apply();
                    new Handler().postDelayed(() -> listener.onItemClick(items.get(position)), 400);

                }

        );

        holder.itemCheckbox.setChecked(isMyValueChecked);

    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public interface onItemClickListener {
        void onItemClick(ResidentialFireBaseInfo itemAtPosition);

    }


    public class FireInfoViewHolder extends RecyclerView.ViewHolder {

        private AppCompatTextView itemText;
        public AppCompatCheckBox itemCheckbox;
        private ResidentialFireBaseInfo fireBaseInfo;

        public FireInfoViewHolder(@NonNull View itemView) {
            super(itemView);
            initializeUi();
        }

        private void initializeUi() {
            itemText = itemView.findViewById(R.id.item_text);
            itemCheckbox = itemView.findViewById(R.id.item_check_box);


        }

        public void bind(ResidentialFireBaseInfo fireBaseInfo) {
            this.fireBaseInfo = fireBaseInfo;
            itemText.setText(fireBaseInfo.getTitle());
        }
    }
}