在Android中的ListView CheckBox中设置SelectedValue

时间:2014-04-19 16:41:12

标签: android listview checkbox android-listview

我在Android中ListView使用CheckBox。工作正常。

现在,我想根据参数在CheckBox中设置选定值。因此,在加载列表时,如果参数用户为是,则检查Checkbox否则不检查。在这里,在下面基于country.getUser()的代码中,我想检查CheckBox。资料来源:ListView CheckBox in Android

我的代码:

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;

  }
 }

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

您可以使用setChecked选中复选框,具体取决于此值

if(country.getUser().equalsIgnoreCase("Yes")){
        holder.checkBox.setChecked(true);
    }
    else {
        holder.checkBox.setChecked(false);
    }