我有一个问题:如果我选中一个复选框并在我点击另一个选项卡后我赶紧前一个选项卡,那么checkked now复选框之前就不会被检查...所以我想保存并从文件中读取只选中复选框。 我使用了共享偏好,但它不起作用.... 所以,我的问题是:
我如何只在复选框中写入和读取文件?
我希望你能帮助我! 感谢每一个人!
这是我的代码:
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(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);
row.setTag(holder);
} else {
holder = (PlanetHolder) row.getTag();
}
final Planet p = planetList.get(position);
SharedPreferences settings = context.getSharedPreferences("data", Context.MODE_PRIVATE);
boolean Checked = settings.getBoolean("Material", false);
holder.chkBox.setChecked(Checked);
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 settings = context.getSharedPreferences("data", Context.MODE_PRIVATE);
settings.edit().putBoolean("Material", true).apply();
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());
}
});
} 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;
}
}
FRAGMENT:
public class MyListFragment extends Fragment implements
android.widget.CompoundButton.OnCheckedChangeListener {
ListView lv;
ArrayList<Planet> planetList;
PlanetAdapter plAdapter;
BirraAdapter biAdapter;
PlanetAdapter.PlanetHolder holder;
//boolean mCheckBoxValue;
private CheckBox chkBox;
@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, "€"));
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);
*//*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();
*/
}
}
答案 0 :(得分:1)
单击时,您可以保存boolean
变量,例如:
boolean isChecked;
if(isChecked(){
checked = true;
}else{
checked = false;}
saveInFile();
您是否需要将代码保存在文件中?
private void loadFile(){
FileInputStream fis = null;
ObjectInputStream ois = null;
if(this.isExternalStorageAvailable()) {
try {
fis = new FileInputStream(
new File(this.getExternalFilesDir("file"), "file.dat"));
ois = new ObjectInputStream(fis);
this.checked = (Boolean)ois.readObject();
} catch (FileNotFoundException e) {
//Toast.makeText(main, "File doesn't exist", Toast.LENGTH_SHORT).show();
} catch (StreamCorruptedException e) {
//Toast.makeText(main, "Error opening file", Toast.LENGTH_SHORT).show();
} catch(EOFException e){
try {
if(ois != null)
ois.close();
if(fis != null)
fis.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (IOException e) {
//Toast.makeText(main, "File read error", Toast.LENGTH_SHORT).show();
} catch (ClassNotFoundException e) {
//Toast.makeText(main, "Class Booelan doesn't exist", Toast.LENGTH_SHORT).show();
}
}
}
private void saveInFile(){
if(this.isExternalStorageAvailable()){
if(!this.isExternalStorageReadOnly()){
try {
FileOutputStream fos = new FileOutputStream(
new File(this.getExternalFilesDir("file"), "file.dat"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(checked);
oos.close();
fos.close();
} catch (FileNotFoundException e) {
//Toast.makeText(main, "Error opening File", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
//Toast.makeText(main, "Error saving File", Toast.LENGTH_SHORT).show();
}
}
}
}
private static boolean isExternalStorageAvailable(){
String estadoSD = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(estadoSD))
return true;
return false;
}
private static boolean isExternalStorageReadOnly(){
String estadoSD = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED_READ_ONLY.equals(estadoSD))
return true;
return false;
}
答案 1 :(得分:0)
您似乎忘记将检查状态保存到Planet
对象。
因此,当您回来时,ListView
中的复选框将取消选中
holder.chkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
p.setSelected(finalHolder.chkBox.isChecked()); //add this
if (finalHolder.chkBox.isChecked()) {
...
} else {
...
}
}
});
答案 2 :(得分:0)
您已将片段状态存储在onSaveInstanceState()方法中。
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState); // store value in key , value order
outState.putInt("curChoice", mCurCheckPosition);
}
稍后,您可以使用onActivityCreated()方法。
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore last state for checked position.
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
}