android simples 结构,android – 如何在simple_list_item_2中构造和显示信息?
我從我的(測試)數據庫中獲取客戶信息列表,我想顯示它.客戶由Customer類表示,包括姓名,信息和注釋成員.它的toString方法只返回名稱.我創建了僅使用simple_list_item_1布局的DemoDatabaseMainActivity,因此只顯示客戶的名稱 – 如下所示:
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 values = datasource.getAllCustomers();
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
...
}
它運作得很好;但是,我想學習下一步……
我想修改代碼,以便我可以使用android.R.layout.simple_list_item_2,其中名稱將在第一行,而信息注釋在第二行?應該實現什么而不是Customer.toString(),以及我應該使用什么適配器或什么?
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 values = datasource.getAllCustomers();
TwolineAdapter adapter = new TwolineAdapter(this, values); // here the difference
setListAdapter(adapter);
}
...
}
所以,我以這種方式添加了我的TwolineAdapter類:
public class TwolineAdapter extends ArrayAdapter {
private List objects;
public TwolineAdapter(Context context, List 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;
}
}
但它沒有用(顯然是因為我的一些錯誤).注意超級構造函數代碼調用中的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 {
private List objects;
public TwolineAdapter(Context context, List 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.我接下來該怎么辦? (我的結論是我在構造函數中做錯了.我是對的嗎?問題出在哪里?)
總結
以上是生活随笔為你收集整理的android simples 结构,android – 如何在simple_list_item_2中构造和显示信息?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HTML自动获取地址,网页中自动获取经纬
- 下一篇: 小米合作鸿蒙系统了么,小米等国产手机会使