【发布时间】:2013-04-17 14:20:04
【问题描述】:
我从我的(测试)数据库中获取了客户信息列表,我想显示它。客户由具有name、info 和note 成员的Customer 类表示。它的toString 方法只返回name。我创建了仅使用simple_list_item_1 布局的DemoDatabaseMainActivity,因此仅显示客户的name - 如下所示:
public class DemoDatabaseMainActivity extends ListActivity {
private CustomerDataSource datasource;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
datasource = new CustomerDataSource(this);
datasource.open();
List<Customer> values = datasource.getAllCustomers();
ArrayAdapter<Customer> adapter = new ArrayAdapter<Customer>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
...
}
它工作得很好;但是,我想学习下一步...
我想修改代码,以便可以使用android.R.layout.simple_list_item_2,其中name 位于第一行,info + note 位于第二行?应该实现什么而不是Customer.toString(),我应该使用什么适配器或其他什么?
更新基于 Patric 的评论 https://stackoverflow.com/a/16062742/1346705 -- 对此,我希望修改后的解决方案是这样的:
public class DemoDatabaseMainActivity extends ListActivity {
private CustomerDataSource datasource;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
datasource = new CustomerDataSource(this);
datasource.open();
List<Customer> values = datasource.getAllCustomers();
TwolineAdapter adapter = new TwolineAdapter(this, values); // here the difference
setListAdapter(adapter);
}
...
}
所以,我以这种方式添加了我的TwolineAdapter 类:
public class TwolineAdapter extends ArrayAdapter<Customer> {
private List<Customer> objects;
public TwolineAdapter(Context context, List<Customer> objects) {
super(context, android.R.layout.simple_list_item_2, objects);
this.objects = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView text1 = (TextView) view.findViewById(android.R.id.text1);
TextView text2 = (TextView) view.findViewById(android.R.id.text2);
text1.setText(objects.get(position).getName());
text2.setText(objects.get(position).getInfo()
+ " (" + objects.get(position).getNote() + ")");
return view;
}
}
但它不起作用(显然是因为我的一些错误)。注意super 构造函数代码调用中的simple_list_item_2。运行时,代码显示如下错误日志消息:
E/ArrayAdapter(27961): You must supply a resource ID for a TextView
我想问你问题出在哪里。试图找出原因,我修改了TwolineAdapter,使其与simple_list_item_1的原始工作方式相同
public class TwolineAdapter extends ArrayAdapter<Customer> {
private List<Customer> objects;
public TwolineAdapter(Context context, List<Customer> objects) {
super(context, android.R.layout.simple_list_item_1, objects);
this.objects = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView view = (TextView)super.getView(position, convertView, parent);
view.setText(objects.get(position).getInfo()); // displaying a different info
return view;
}
}
为了确保覆盖的getView 有效,我显示了客户信息的不同部分。而且效果很好。也就是说,不是显示一般的toString方法,而是显示我特定的getInfo的结果。
无论如何,我需要使用simple_list_item_2。接下来我该怎么办? (我的结论是我在构造函数中做错了。我是对的吗?问题出在哪里?)
【问题讨论】: