我有一个ListView
,其中每个项目都包含一些text(name,id)
和一个复选框。有一个按钮可以从ListView
页面返回。因此,用户检查了一些项目并返回到上一页。还有一个按钮是这个页面返回ListView
页面。当他/她回来时,我想向他/她展示他/她之前选择了哪些项目。
我知道SharedPreferences
,但我不想使用它,因为我不想在用户重新启动应用程序时保存该状态。我只希望在应用程序运行时使用它。我做了一些工作,保存他选择的数据,并在他回来时检查它。但我无法检查复选框。我希望有人会说我在这里做错了什么。我使用xml中的复选框,而不是以编程方式。
public class MyCustomArrayAdapter extends ArrayAdapter<Model> {
private final List<Model> list;
private final Activity context;
public static ArrayList<String> friendName=new ArrayList<String>();
public static ArrayList<String> friendBirthdate=new ArrayList<String>();
public static ArrayList<String> friendId=new ArrayList<String>();
public static ArrayList<String> getSelectedFriendId;
public MyCustomArrayAdapter(Activity context, List<Model> list)
{
super(context, R.layout.list_layout, list);
this.context = context;
this.list = list ;
}
public static int count=0;
static class ViewHolder
{
protected TextView text, sub;
protected CheckBox checkbox;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = null;
if (convertView ==null)
{
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.list_layout, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView)view.findViewById(R.id.label);
viewHolder.text.setTextColor(Color.WHITE);
viewHolder.sub = (TextView)view.findViewById(R.id.sub);
viewHolder.sub.setTextColor(Color.GRAY);
viewHolder.checkbox = (CheckBox)view.findViewById(R.id.check);
if(SelectionPage.get_selectedFriendId()!=null) //checking whether user checked something earlier
{
getSelectedFriendId=SelectionPage.get_selectedFriendId(); //get checked userid from when user selects something
for( int x = 0 ; x < getSelectedFriendId.size() ; x++ )
{
for(int a=0;a<list.size();a++)
{
if(list.get(a).getId().contains(getSelectedFriendId.get(x)))
{
Toast.makeText( context, "matched..", Toast.LENGTH_SHORT).show();
viewHolder.checkbox.setChecked(true); //this doesn't check checkbox which is the problem!
}
}
}
}
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked)
{
Model element = (Model)viewHolder.checkbox.getTag();
if(buttonView.isChecked())
{
count++;
friendName.add(element.getName().toString());
friendBirthdate.add(element.getPlace().toString());
friendId.add(element.getId().toString());
}
else
{
friendName.remove(element.getName().toString());
friendBirthdate.remove(element.getPlace().toString());
friendId.remove(element.getId().toString());
count--;
}
}
});
view.setTag(viewHolder);
viewHolder.checkbox.setTag(list.get(position));
}
else
{
view = convertView;
((ViewHolder)view.getTag()).checkbox.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
holder.sub.setText( list.get(position).getPlace());
return view;
}
}