在Android的ListView CheckBox中设置SelectedValue
问题描述:
我在Android的 CheckBox
中使用 ListView
。
现在,我想基于参数在 CheckBox
中设置选定值。因此,在加载列表时,如果参数用户为是,请检查复选框
,否则不进行检查。在下面的基于country.getUser()的代码中,我要检查 CheckBox
。来源: Android中的ListView CheckBox
我的代码:
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;
}
}
请对此提供帮助。
答
您可以使用 setChecked
来检查复选框,具体取决于以下值此
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);
}