So I kinda screwed up while making the checkedtextviews, didn’t realise i needed to save the state, I don’t know how exactly to do it. Any advice would be greatly appreciated.
CheckedTextView C1,C2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_anime2); C1 = findViewById(R.id.C1); C2 = findViewById(R.id.C2); C1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View V) { C1.toggle(); if(C1.isChecked() == true) { C1.setBackgroundResource(R.drawable.cb_background); } else { C1.setBackgroundResource(R.drawable.cb_background_default); } } }); C2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { C2.toggle(); if(C2.isChecked() == true) { C2.setBackgroundResource(R.drawable.cb_background); } else { C2.setBackgroundResource(R.drawable.cb_background_default); } } });
Advertisement
Answer
I’m not familiar saving data yet, I know that there is a lot of ways of doing that so i’ll give one example:
Before that here is a guide like that can help: Save key-value data
Here is a example of what i did.You could put the variable as a global if you need.
CheckedTextView C1,C2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_anime2); C1 = findViewById(R.id.C1); C2 = findViewById(R.id.C2); C1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View V) { C1.toggle(); if(C1.isChecked() == true) { C1.setBackgroundResource(R.drawable.cb_background); } else { C1.setBackgroundResource(R.drawable.cb_background_default); } savePreferences(); } }); C2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { C2.toggle(); if(C2.isChecked() == true) { C2.setBackgroundResource(R.drawable.cb_background); } else { C2.setBackgroundResource(R.drawable.cb_background_default); } savePreferences(); } }); } //To save the status of each textCheck public void savePreferences(){ SharedPreferences preferences = getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("c1",C1.isChecked); editor.putBoolean("c2",C2.isChecked); editor.apply(); } //to get each textCheckSaved public void getSavedPreferences(){ SharedPreferences preferences = getPreferences(MODE_PRIVATE); C1.setChecked(preferences.getBoolean("c1",C1.isChecked)) C2.setChecked(preferences.getBoolean("c2",C2.isChecked)) } //to clean the data that you save public void cleanSavedPreferences(){ sharedPreferences = getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.remove("c1").remove("c2"); editor.apply(); }