我已經得到了使用自定義BaseAdapter(MyBaseAdapter)填充一個ListView:添加一個新行到ListView使得它上面的那些消失
public class MyBaseAdapter extends BaseAdapter
{
private View renderer;
List<MyItemModel> items;
public MyBaseAdapter(View renderer) {
this.renderer = renderer;
}
public void setModel(List<MyItemModel> items)
{
this.items = items;
notifyDataSetChanged();
}
@Override
public int getCount()
{
return items != null ? items.size() : 0;
}
@Override
public Object getItem(int position)
{
return items != null ? items.get(position) : null;
}
@Override
public long getItemId(int position)
{
return items != null ? items.get(position).id : -1;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = renderer;
}
MyItemModel item = items.get(position);
// replace those R.ids by the ones inside your custom list_item layout.
TextView timeText = (TextView) convertView.findViewById(R.id.timeText);
timeText.setText(item.time);
ToggleButton button = (ToggleButton) convertView.findViewById(R.id.toggleButton);
button.setOnClickListener(item.listener);
ImageView coinImage = (ImageView) convertView.findViewById(R.id.coinImage);
coinImage.setImageResource(R.drawable.ic_refresh);
return convertView;
}
}
它使用這些物品
public class MyItemModel
{
String time;
long id;
OnClickListener listener = new OnClickListener(){
@Override
public void onClick(View v) {
Log.d("app", "whatever");
}
};
}
填充
我從我的主類使用代碼添加項目是這樣的:
private void setUpList()
{
myListModel = new ArrayList<MyItemModel>();
MyItemModel item = new MyItemModel();
item.time = "12:00";
item.id = 0;
myListModel.add(item);
//if I add a few more items here, it still only shows the bottom one
LayoutInflater li = getLayoutInflater();
//alarm_list_item is a table row
View view = li.inflate(R.layout.alarm_list_item, null);
adapter = new MyBaseAdapter(view);
adapter.setModel(myListModel);
setListAdapter(adapter);
listView = getListView();
listView.setTextFilterEnabled(true);
}
而且工作正常unti l當發生這種情況時,我將其他項目添加到列表中(注意上面的行是空白的。如果我添加多行,除最後一行之外的所有行都是空白的。)
任何想法發生了什麼?
非常感謝!我想我需要更多地瞭解適配器和渲染器等等! –