选择一个单选按钮,当我回到这个活动时,选择仍然存在?
问题描述:
自定义列表和包含单选按钮,我想选择一个单选按钮,它的工作原理。但我想保存我选择的那个raidbutton。 我使用sharedpreference,但我无法做到这一点。我知道sharedpreference是在android中节省价值的好方法。 对不起英文不好。 请帮我。选择一个单选按钮,当我回到这个活动时,选择仍然存在?
public class rowadapter extends ArrayAdapter<String> {
private final Activity context;
int layoutResourceId;
private final String[] web;
private final Integer[] imageId;
int selectedPosition = -1;
SharedPreferences sharedPref;
public rowadapter(Activity context,String[] web, Integer[] imageId) {
super(context,R.layout.item_listview, web);
this.context = context;
this.web = web;
this.imageId = imageId;
sharedPref = context.getSharedPreferences("position",Context.MODE_PRIVATE);
}
public View getView(final int position, View row, ViewGroup parent)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
backgroundholder holder = null;
View rowView=row;
rowView= inflater.inflate(R.layout.item_listview, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText(web[position]);
imageView.setImageResource(imageId[position]);
holder = new backgroundholder();
holder.radiobutton = (RadioButton)rowView.findViewById(R.id.radiobutton);
holder.radiobutton.setChecked(position == selectedPosition);
holder.radiobutton.setTag(position);
int checkedpos=sharedPref.getInt("poistion",-1);
if(checkedpos==position)
{
holder.radiobutton.setChecked(true);
}
holder.radiobutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
selectedPosition = (Integer)view.getTag();
RadioButton radio = (RadioButton)view;
if(radio.isChecked())
{
Editor editor=sharedPref.edit();
editor.putInt("position", selectedPosition);
editor.commit();
}
notifyDataSetInvalidated();
}
});
return rowView;
static class backgroundholder
{
RadioButton radiobutton;
}
答
它看起来像一个拼写错误,你写的:
int checkedpos=sharedPref.getInt("poistion",-1);
,但它应该是:
int checkedpos=sharedPref.getInt("position",-1);
出于这个原因,我通常喜欢用一个常数,所以你做一个实例变量,如:
public static final String POSITION = "position";
然后访问像这样的值:
int checkedpos = sharedPref.getInt(POSITION, -1);
///...
editor.putInt(POSITION, selectedPosition);
这将更容易发现拼写错误。
哦是的......:S:S:S:S:S:S:S非常感谢 – user3631823
@ user3631823没有probs,你会如此友善接受这个答案吗?谢谢 – user184994
我怎么接受?我不能投票,直到nw – user3631823