Set SelectedValue in ListView CheckBox in Android

孤街醉人 提交于 2019-12-11 13:27:29

问题


I am using ListView in CheckBox in Android. It is working fine.

Now, I want to set Selected Value in CheckBox based on Parameter. So on the loading of the list, if Parameter User is Yes then check that Checkbox else does not check. Here, in below code based on country.getUser(), I want to check CheckBox. Source : ListView CheckBox in Android

My Code :

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;

  }
 }

Please help me regarding this.


回答1:


You can use setChecked to check the checkbox depends on the value like this

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


来源:https://stackoverflow.com/questions/23172676/set-selectedvalue-in-listview-checkbox-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!