繁体   English   中英

Android:需要在自定义适配器列表视图中保存复选框状态

[英]Android: Need to save checkbox state in a custom adapter listview

我需要能够保存复选框的状态。 当应用关闭时,它应保存选中了哪些复选框,当应用重新启动时,应在启动时选中已选中的复选框。 它使用自定义适配器列表视图。 感谢您的时间。

主要活动

public class MainActivity extends Activity {

MyCustomAdapter dataAdapter = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Generate list View from ArrayList
    displayListView();

}



private void displayListView() {

    //Array list of countries
    ArrayList<Country> countryList = new ArrayList<Country>();
    Country country = new Country("","Challenge 1",false);
    countryList.add(country);
    country = new Country("ALB","Albania",false);
    countryList.add(country);
    country = new Country("DZA","Algeria",false);
    countryList.add(country);
    country = new Country("ASM","American Samoa",false);
    countryList.add(country);
    country = new Country("AND","Andorra",false);
    countryList.add(country);
    country = new Country("AGO","Angola",false);
    countryList.add(country);
    country = new Country("AIA","Anguilla",false);
    countryList.add(country);

    //create an ArrayAdaptar from the String Array
    dataAdapter = new MyCustomAdapter(this,
            R.layout.country_info, countryList);
    ListView listView = (ListView) findViewById(R.id.listView1);
    // Assign adapter to ListView
    listView.setAdapter(dataAdapter);


    listView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            // When clicked, show a toast with the TextView text
            Country country = (Country) parent.getItemAtPosition(position);
            Toast.makeText(getApplicationContext(),
                    "Clicked on Row: " + country.getName(),
                    Toast.LENGTH_LONG).show();
        }
    });

}

private class MyCustomAdapter extends ArrayAdapter<Country> {

    private ArrayList<Country> countryList;

    public MyCustomAdapter(Context context, int textViewResourceId,
                           ArrayList<Country> countryList) {
        super(context, textViewResourceId, countryList);
        this.countryList = new ArrayList<Country>();
        this.countryList.addAll(countryList);
    }

    private class ViewHolder {
        TextView code;
        CheckBox name;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder = null;
        Log.v("ConvertView", String.valueOf(position));

        if (convertView == null) {
            LayoutInflater vi = (LayoutInflater)getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(R.layout.country_info, null);

            holder = new ViewHolder();
            holder.code = (TextView) convertView.findViewById(R.id.code);
            holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
            convertView.setTag(holder);

            holder.name.setOnClickListener( new View.OnClickListener() {
                public void onClick(View v) {
                    CheckBox cb = (CheckBox) v ;
                    Country country = (Country) cb.getTag();
                    Toast.makeText(getApplicationContext(),
                            "Clicked on Checkbox: " + cb.getText() +
                                    " is " + cb.isChecked(),
                            Toast.LENGTH_LONG).show();
                    country.setSelected(cb.isChecked());
                }
            });
        }
        else {
            holder = (ViewHolder) convertView.getTag();
        }

        Country country = countryList.get(position);
        holder.code.setText(" (" +  country.getCode() + ")");
        holder.name.setText(country.getName());
        holder.name.setChecked(country.isSelected());
        holder.name.setTag(country);

        return convertView;

    }

}

}

Country.Java

public class Country {

String code = null;
String name = null;
boolean selected = false;

public Country(String code, String name, boolean selected) {
    super();
    this.code = code;
    this.name = name;
    this.selected = selected;
}

public String getCode() {
    return code;
}
public void setCode(String code) {
    this.code = code;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}

public boolean isSelected() {
    return selected;
}
public void setSelected(boolean selected) {
    this.selected = selected;
}

}

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:padding="10dp"
    android:text="@string/some_text" android:textSize="20sp" />


<ListView android:id="@+id/listView1" android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

country_info.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >

<CheckBox
    android:id="@+id/checkBox1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:text="CheckBox" />

<TextView
    android:id="@+id/code"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/checkBox1"
    android:layout_alignBottom="@+id/checkBox1"
    android:layout_toRightOf="@+id/checkBox1"
    android:text="TextView" />

编辑

我将加载首选项放在getView()方法中,但是一个问题是,sharedPreferences参数中的“ this”带有下划线。 我也将savePreferences()方法和onPause()方法放在代码的末尾,但是holder.name似乎不起作用。

public class MainActivity extends Activity {

MyCustomAdapter dataAdapter = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Generate list View from ArrayList
    displayListView();

}







private void displayListView() {

    //Array list of countries
    ArrayList<Country> countryList = new ArrayList<Country>();
    Country country = new Country("","Challenge 1",false);
    countryList.add(country);
    country = new Country("ALB","Albania",false);
    countryList.add(country);
    country = new Country("DZA","Algeria",false);
    countryList.add(country);
    country = new Country("ASM","American Samoa",false);
    countryList.add(country);
    country = new Country("AND","Andorra",false);
    countryList.add(country);
    country = new Country("AGO","Angola",false);
    countryList.add(country);
    country = new Country("AIA","Anguilla",false);
    countryList.add(country);

    //create an ArrayAdaptar from the String Array
    dataAdapter = new MyCustomAdapter(this,
            R.layout.country_info, countryList);
    ListView listView = (ListView) findViewById(R.id.listView1);
    // Assign adapter to ListView
    listView.setAdapter(dataAdapter);


    listView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            // When clicked, show a toast with the TextView text
            Country country = (Country) parent.getItemAtPosition(position);
            Toast.makeText(getApplicationContext(),
                    "Clicked on Row: " + country.getName(),
                    Toast.LENGTH_LONG).show();
        }
    });

}

private class MyCustomAdapter extends ArrayAdapter<Country> {

    private ArrayList<Country> countryList;

    public MyCustomAdapter(Context context, int textViewResourceId,
                           ArrayList<Country> countryList) {
        super(context, textViewResourceId, countryList);
        this.countryList = new ArrayList<Country>();
        this.countryList.addAll(countryList);
    }

    private class ViewHolder {
        TextView code;
        CheckBox name;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder = null;
        Log.v("ConvertView", String.valueOf(position));

        if (convertView == null) {
            LayoutInflater vi = (LayoutInflater)getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(R.layout.country_info, null);

            holder = new ViewHolder();
            holder.code = (TextView) convertView.findViewById(R.id.code);
            holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
            convertView.setTag(holder);



            SharedPreferences sharedPreferences = PreferenceManager
                    .getDefaultSharedPreferences(this);
            boolean checkBoxValue = sharedPreferences.getBoolean("CheckBox_Value", false);
            if (checkBoxValue) {
                holder.name.setChecked(true);
            } else {
                holder.name.setChecked(false);
            }




            holder.name.setOnClickListener( new View.OnClickListener() {
                public void onClick(View v) {
                    CheckBox cb = (CheckBox) v ;
                    Country country = (Country) cb.getTag();
                    Toast.makeText(getApplicationContext(),
                            "Clicked on Checkbox: " + cb.getText() +
                                    " is " + cb.isChecked(),
                            Toast.LENGTH_LONG).show();
                    country.setSelected(cb.isChecked());
                }
            });
        }
        else {
            holder = (ViewHolder) convertView.getTag();
        }

        Country country = countryList.get(position);
        holder.code.setText(" (" +  country.getCode() + ")");
        holder.name.setText(country.getName());
        holder.name.setChecked(country.isSelected());
        holder.name.setTag(country);

        return convertView;

    }

}

private void savePreferences(String key, boolean value) {
    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean(key, value);
    editor.commit();
}

@Override
public void onPause(){
    super.onPause();
    savePreferences("CheckBox_Value", holder.name.isChecked());
}

}

您可以使用Android的“共享的偏好设置”来保存复选框状态:

编辑:

要分离关注点,您应该在模型中保留持久性逻辑:

导入android.content.Context; 导入android.content.SharedPreferences;

public class Country {

private static final String PREFERENCES_NAMESPACE = "checkboxes_states";

String code = null;
String name = null;
boolean selected = false;
private SharedPreferences mSettings;
private SharedPreferences.Editor mEditor;

public Country(Context context, String code, String name, boolean selected) {
    super();
    this.code = code;
    this.name = name;
    mSettings = context.getSharedPreferences(PREFERENCES_NAMESPACE, 0);
    mEditor = mSettings.edit();
    setSelected(mSettings.getBoolean(code, selected));
}

public String getCode() {
    return code;
}

public void setCode(String code) {
    this.code = code;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public boolean isSelected() {
    return selected;
}

public void setSelected(boolean selected) {
    if(this.selected != selected) { // update if changed
        mEditor.putBoolean(getCode(), selected);
        mEditor.commit();
        this.selected = selected;
    }
}
}

初始化Country对象时,请不要忘记传递应用程序上下文。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM