在 MainActivity 我有一个 ListView 显示如下:
[复选框] [文本视图] [按钮]
在右上角有一个添加按钮。当我单击该按钮时,它会在列表视图中添加一项。
MyItem item = new MyItem(itemName);
myItemsList.add(item);
adapter.notifyDataSetChanged();
“MyItem”是 pojo 类,“itemName”是字符串值。“myItemList”是 ArrayList。
所以这个项目完美地添加到 ListView 但是当我再次加载活动或重新启动应用程序时,不应显示值。
我怎么解决这个问题?
提前致谢。
编辑
这是 ArrayAdapter getView方法
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
MyItem cell = (MyItem) getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
SharedPreferences sharedPrefs = context.getSharedPreferences(
"sharedPrefs", Context.MODE_PRIVATE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listitem, null);
holder = new ViewHolder();
holder.txtItemName = (TextView) convertView
.findViewById(R.id.tvItemName);
holder.chkItem = (CheckBox) convertView.findViewById(R.id.chkItem);
holder.chkItem
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
int getPosition = (Integer) buttonView.getTag();
// Here we get the position that we have set for the
// checkbox using setTag.
itemList.get(getPosition).setSelected(
buttonView.isChecked());
editor.putBoolean("CheckValue" + getPosition,
buttonView.isChecked());
editor.commit();
// Set the value of checkbox to maintain its state.
}
});
convertView.setTag(holder);
convertView.setTag(R.id.tvItemName, holder.txtItemName);
convertView.setTag(R.id.chkItem, holder.chkItem);
} else {
holder = (ViewHolder) convertView.getTag();
}
editor = sharedPrefs.edit();
holder.chkItem.setTag(position); // This line is important.
holder.txtItemName.setText(itemList.get(position).getName());
holder.chkItem.setChecked(sharedPrefs.getBoolean("CheckValue"
+ position, false));
return convertView;
}
编辑
public String[] items = new String[]{"A","B","C"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lvItemName = (ListView) findViewById(R.id.lvItemName);
imgAdd = (ImageView) findViewById(R.id.imgAdd);
myItemsList = new ArrayList<MyItem>();
for (int i = 0; i < items.length; i++) {
MyItem item = new MyItem(items[i]);
myItemsList.add(item);
}
adapter = new ItemAdapter(this, R.layout.listitem, myItemsList);
lvItemName.setAdapter(adapter);
lvItemName.setOnItemClickListener(this);
// ImageView Add Click
imgAdd.setOnClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
MyItem planet = adapter.getItem(position);
planet.toggleChecked();
ViewHolder viewHolder = (ViewHolder) view.getTag();
viewHolder.getCheckBox().setChecked(planet.isSelected());
Log.i("Checked::", "" + viewHolder.getCheckBox().isChecked());
}