【发布时间】:2015-03-31 21:22:18
【问题描述】:
我为ListView 创建了一个自定义适配器,每行都有一个CheckBox。每次检查Checkbox 时,我都想对ListView 中的选定项目触发操作,但getItem(position) 总是返回ListView 中的最后一个项目。
设置适配器:
public void onPostExecuteSearchRequestedCars(JSONArray array){
List<JSONObject> list = new ArrayList<>(array.length());
try {
for(int i = 0 ; i < array.length() ; i++){
JSONObject temp = array.getJSONObject(i);
list.add(temp);
}
} catch (JSONException e) {
Log.e(e.getClass().getName(),"There is no JSONObject in the JSONArray", e);
}
// Create and set the custom listView.
adapter = new CustomSpecificCar(this, list, this);
lv = (ListView) findViewById(R.id.lvCars);
lv.setAdapter(adapter);
}
自定义适配器:
public class CustomSpecificCar extends ArrayAdapter<JSONObject>{
ListSpecificCars caller;
private JSONObject currentJson;
private CheckBox cbSelectedCar;
private List<JSONObject> list;
public CustomSpecificCar(Context ctxt, List<JSONObject> list, ListSpecificCars caller){
super(ctxt, R.layout.custom_specific_car_row, list);
this.caller = caller;
this.list = list;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
final View customView = inflater.inflate(R.layout.custom_specific_car_row, parent, false);
// Set the reference of the layout
currentJson = caller.getItem(position);
cbSelectedCar = (CheckBox)customView.findViewById(R.id.cbSelectedCar);
TextView tvBrand = (TextView)customView.findViewById(R.id.tvBrand);
TextView tvModel = (TextView)customView.findViewById(R.id.tvModel);
TextView tvOwnerEditable = (TextView)customView.findViewById(R.id.tvOwnerEditable);
TextView tvPriceEditable = (TextView)customView.findViewById(R.id.tvEstimatedPriceEditable);
try {
tvBrand.setText(currentJson.getString("brand"));
tvModel.setText(currentJson.getString("model"));
tvOwnerEditable.setText(currentJson.getString("owner"));
} catch (JSONException e) {
Log.e(e.getClass().getName(), "JSONException", e);
}
cbSelectedCar.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
caller.updateClickedUsername(currentJson, true); // Add to the List
try {
Log.d("Has been checked ", currentJson.getString("brand"));
} catch (JSONException e) {
e.printStackTrace();
}
}
else
caller.updateClickedUsername(currentJson, false); // Delete from the List
}
});
return customView;
}
@Override
public int getCount() {
return list.size();
}
}
编辑 我在调用者类中添加了一个 getItem:
public JSONObject getItem(int position){
return list.get(position);
}
我怀疑是这个错误:每次将JSONObject 添加到列表中时,我都会调用getView(),并在全局变量中设置此对象的值。 (private JSONObject currentJson)。
你能让我走对路吗?
编辑 2
终于实现了,每次都使用getItem(position)而不是currentJson。
【问题讨论】:
-
最佳实践是对 List/GridView 使用 Holder。
标签: java android listview checkbox