ListView是Android软件开发中非常重要组件之一,基本上是个软件基本都会使用ListView 。
今天我们初始ListView并实现其适配器BaseAdapter的相关方法。
先看ListView官方API:
A view that shows items in a vertically scrolling list. The items come from the ListAdapter
associated with this view.
我们在布局文件中添加ListView控件:
<ListView
android:id="@+id/test_lv_main"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
ps:Android中所有控件都可以在xml中显示出来,所有控件首字母都必须大写,初始化findViewById。
在代码中初始化控件:
private ListView test_lv_main;
···
test_lv_main = (ListView) findViewById(R.id.test_lv_main);
ListView控件比较特殊,显示数据需要适配器,我们跟随刚才的API进入ListAdapter接口,
Extended Adapter
that is the bridge between a ListView
and the data that backs the list. Frequently that data comes from a Cursor, but that is not required. The ListView can display any data provided that it is wrapped in a ListAdapter.
然而实现该接口后发现要实现的方法太多,所以,转而寻找他的实现类。
我们看一下他的子类:
Known Indirect Subclasses
Common base class of common implementation for an Adapter
that can be used in both ListView
(by implementing the specializedListAdapter
interface} and Spinner
(by implementing the specialized SpinnerAdapter
interface.
这里重点说一下getCount方法,它决定我们在ListView中展示几条数据,这里我们直接返回10,即展示10条。
还有getView方法,它获取一个View并将其作为ListView的一个条目展示出来,这里我们自定义一个TextView。
private class testAdapter extends BaseAdapter{
//一共展示多少条数据
@Override
public int getCount() {
return 10;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
//获取View,作为ListView的一个条目显示
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
TextView tv = new TextView(MainActivity.this);
tv.setText("权兴权意-" + position);
return tv;
}
}
test_lv_main.setAdapter(new testAdapter());
运行程序,效果就出来了: