1

我有一个扩展 BaseAdapter 的适配器;其中定义了两个复选框。

public View getView(int position, View convertView, ViewGroup parent) {
    final ViewHolder holder;
    LayoutInflater inflater = context.getLayoutInflater();

    if (convertView == null) {
        convertView = inflater.inflate(R.layout.list_layout, null);
        holder = new ViewHolder();
        holder.apkName = (TextView) convertView.findViewById(R.id.appname);
        holder.category1 = (CheckBox) convertView.findViewById(R.id.category1);
        holder.category1.setTag(position);
        holder.category2 = (CheckBox) convertView.findViewById(R.id.category2);
        holder.category2.setTag(position);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    PackageInfo packageInfo = (PackageInfo) getItem(position);
    Drawable appIcon = packageManager.getApplicationIcon(packageInfo.applicationInfo);
    String appName = packageManager.getApplicationLabel(packageInfo.applicationInfo).toString();
    appIcon.setBounds(0, 0, 55, 55);
    holder.apkName.setCompoundDrawables(appIcon, null, null, null);
    holder.apkName.setCompoundDrawablePadding(15);
    holder.apkName.setText(appName);
    holder.category1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if(holder.category1.isChecked()){
                holder.2.setChecked(false);
                int getPosition = (Integer) holder.category1.getTag();

            }
        }
    });
    holder.category2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
        public void onCheckedChanged(CompoundButton compoundButton, boolean b){
            if(holder.category2.isChecked()){
                holder.category1.setChecked(false);
                int getPosition = (Integer) holder.educational.getTag();
            }
        }
    });

    return convertView;
}

基本上我所拥有的是我所有应用程序的列表,然后是两个复选框,您可以在其中选择一个或两个复选框。据我了解, getPosition 变量将区分复选框对?我想要的是存储用户已选中的复选框。我的想法是首先使用 SharedPreferences 并存储每个 getPosition 的布尔值,但 SharedPreferences 不起作用。那是因为我正在扩展 BaseAdapter 而不是 Activity 吗?如何检索我的主要活动中是否选中了复选框?

4

2 回答 2

1
getSharedPreferences(String, int)

需要有上下文。您始终可以在适配器中传递上下文:

class YourAdapter extends BaseAdapter{
private Context context;
public YourAdapter(Context context){
   this.context=context;
}
//What ever u need to do in this adapter
private doStuff(){
   context.getSharedPreferences(String, int);//ok
}
}

当您在 Activity 中创建此适配器时,只需传入 Activity,例如:

YourAdapter mAdapter=new YourAdapter (this); //in your activity .
于 2013-06-13T16:12:43.283 回答
0

也许我错过了它,但我看不到您要在哪里使用SharedPreferences(我今天确实有一个流浪汉),但是您应该可以使用Context传入的那个。只要您有有效的Activity Context用途

    SharedPreferences prefs = context.getSharedPreferences(...);

另一种选择,如果您不需要它是持久的并且只是在用户当前在应用程序中时存储,则将值设置在class带有static变量的变量中以保存该值并从那里检索它们。但是,如果您希望它持久,那么这SharedPreferences是最好的方法。

于 2013-06-13T16:13:17.487 回答