我想創建一個帶有複選框的列表的BaseAdapter。問題是,當我嘗試獲取每個行項目的標記時,它將返回null。Android BaseAdapter:getTag()返回null
適配器:
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
public class TaskListAdapter extends BaseAdapter {
Context context;
List<Patient> rowItems;
public TaskListAdapter(Context context, List<Patient> items) {
super();
this.context = context;
this.rowItems = items;
}
/*private view holder class*/
private class ViewHolder {
TextView txtTitle;
TextView txtDesc;
CheckBox checkbox;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row, parent, false);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView.findViewById(R.id.firstLine);
holder.txtDesc = (TextView) convertView.findViewById(R.id.secondLine);
holder.checkbox = (CheckBox)convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Patient rowItem = (Patient) getItem(position);
holder.txtDesc.setText(rowItem.getName());
holder.txtTitle.setText(rowItem.getAddress());
holder.checkbox.setChecked(rowItem.isSelected());
holder.checkbox.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
CheckBox checkbox = (CheckBox)v.findViewById(R.id.checkbox);
Patient rowItem = (Patient) checkbox.getTag();
// rowItem is null now for some reason
rowItem.setSelected(checkbox.isChecked());
}
});
return convertView;
}
@Override
public int getCount() {
return rowItems.size();
}
@Override
public Object getItem(int position) {
return rowItems.get(position);
}
@Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
}
和模型類:
public class Patient {
private String name;
private String address;
private boolean checked;
public Patient(String name, String address, boolean checked) {
super();
this.name = name;
this.address = address;
this.checked = checked;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public boolean isSelected() {
return checked;
}
public void setSelected(boolean checked) {
this.checked = checked;
}
}
我試圖讓每一行的標籤,所以我可以保存複選框狀態視圖時滾動。 謝謝。
你能後的logcat的文件以及確切的行logcat狀態錯誤發生在? – Tukajo