[英]Add custom CheckBox to ListView
我在getView()中添加了新的CheckBox(PlanAdapter類)
public View getView(int position, View convertView, ViewGroup viewGroup) {
Plan entry = listPlan.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.walkRow, null, false);
}
LinearLayout d = (LinearLayout)convertView.findViewById(R.id.checkBoxPlace);
TextView distance = (TextView) convertView.findViewById(R.id.distance);
distance.setText(" " + entry.getexerciseNumber());
TextView time = (TextView) convertView.findViewById(R.id.time);
time.setText(" " + entry.getwholeTime());
CheckBox chckStart = new CheckBox(context);
chckStart = entry.getCheckBox();
chckStart.setFocusable(false);
d.addView(chckStart); //here i get force close
return convertView;
}
當我向下滾動它看起來很好,但當我回來並向上滾動它崩潰。
計划類中的getter,setter
public CheckBox getCheckBox(){
return checkBox;
}
public void setCheckBox(CheckBox checkBox){
this.checkBox = checkBox;
}
和我在Main類的checkBox
for (byte i = 0; i < db.planView.size(); i++) {
chcBox = new CheckBox(this);
chcBox.setId(i);
checkboxList.add(chcBox);
listOfPlan.add(new Plan(db.planView.get(i).getText().toString(), db
.count(db.planView.get(i).getText().toString(),
getApplicationContext()), chcBox));
}
日志: http://wklej.to/RpBvr/html
: http://wklej.to/RpBvr/html
您正嘗試將每個復選框添加到多個父視圖中,這是您無法做到的...
但是ListView已經有很多功能來實現復選框,這里有一種方法:
public class Example extends Activity implements OnItemClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] array = {"one", "two", "three"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, array);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.v("Example", "ItemClick: " + ((ListView) parent).getCheckedItemPosition());
}
}
您只需傳遞自己的XML文件即可自定義布局。
加成
每次顯示一行時,您都會刷新entry
數據並嘗試添加復選框,這就是您可以向下滾動而不是向上滾動的原因。 如果要保留自定義適配器,只需檢查該行是否已初始化,然后再嘗試添加相同的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.