我在自定义适配器中有一个arrayList,包含一些字符串和复选框。并且我想在某些条件下自动设置复选框,但是如何设置代码以便自动选中复选框。
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if(convertView == null)
vi = inflater.inflate(R.layout.list_row, null);
TextView no = (TextView)vi.findViewById(R.id.txt_no);
TextView code = (TextView)vi.findViewById(R.id.txt_code);
TextView name = (TextView)vi.findViewById(R.id.txt_asset);
TextView dept = (TextView)vi.findViewById(R.id.txt_dept);
CheckBox status = (CheckBox)vi.findViewById(R.id.cb_stat);
HashMap<String, String> asset = new HashMap<String, String>();
asset = data.get(position);
//Setting all values in listview
no.setText(asset.get(ListLocationActivity.KEY_NO));
code.setText(asset.get(ListLocationActivity.KEY_CODE));
name.setText(asset.get(ListLocationActivity.KEY_NAME));
dept.setText(asset.get(ListLocationActivity.KEY_DEPT));
return vi;
}
当我得到结果时,这是我的条件,我想设置选中结果与arraylist中的代码相适应的复选框
for (int i = 0; i < assetList.size(); i++) {
if (assetList.get(i).get(KEY_CODE).equals(scanAsset)){
//set checked in certain list asset
//(Here i confused how i can set the checkbox in list suitable with the code asset)
Log.i("Asset code is ", scanAsset);
}
}
此代码在复选框中没有设置值时工作正常,任何人都可以帮我解决这个问题。 。 。 。 谢谢你
答案 0 :(得分:1)
我建议使用实际的对象而不是HashMap,但这超出了这个问题的范围
我会调整您的getView
来回添加此行,然后再返回
status.setChecked(asset.containsKey(ListLocationActivity.KEY_CHECKED));
显然创建了一个新的静态密钥,用于检查,不确定定义的位置
然后一旦得到你的扫描结果,你就引用了上面这个,所以我会修改它:
for (int i = 0; i < assetList.size(); i++) {
HashMap<String, String> asset = assetList.get(i);
if (asset.get(KEY_CODE).equals(scanAsset)){
asset.put(KEY_CHECKED, "Checked");
Log.i("Asset code is ", scanAsset);
}
}
adapter.notifyDataSetChanged();
所以我们所做的是我们为你的适配器创建了一个新的属性来关闭,然后如果你正在构建适配器中的视图的资产有那个键,那么我们要检查复选框,否则我们想要不检查它。
答案 1 :(得分:0)
创建一个模型对象(此处称为AssetsWrapper)并在其中设置一个布尔值。
// Model wrapper class
class AssetsWrapper {
HashMap<String, String> mAssets;
boolean mBoolean;
}
// Your code that checks the CheckBox
for (int i = 0; i < assetList.size(); i++) {
if (assetList.get(i).get(KEY_CODE).equals(scanAsset)){
assetList.get(i).mBoolean = true;
}
adapter.notifyDataSetChanged();
}
// YOUR ADAPTER CODE --------------------------------------------
// Constructor (notice that the ArrayList has changed)
public LazyAdapter(Activity a, ArrayList<AssetsWrapper> d) {
activity = a;
data = d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(int position, View convertView, ViewGroup parent) {
// ...
CheckBox status = (CheckBox)vi.findViewById(R.id.cb_stat);
AssetsWrapper aw = getItem(position);
// Here, the adapter reads the value from the model object.
status.setChecked(aw.mBoolean);
// ...
return vi;
}