0

customlist 并包含单选按钮,我想选择一个单选按钮,它可以工作。但我想保存我选择的那个raidobutton。我使用了 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;
}
4

1 回答 1

1

它看起来像一个拼写错误,你已经写了:

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

这将更容易发现拼写错误。

于 2014-05-15T12:49:36.697 回答