listview作为一个列表控件,他和普通的列表一样,可以自己设置表头与表尾:以及分割线,可供我们设置的属性如下:
- footerDividersEnabled:是否在footerView(表尾)前绘制一个分隔条,默认为true
- headerDividersEnabled:是否在headerView(表头)前绘制一个分隔条,默认为true
- divider:设置分隔条,可以用颜色分割,也可以用drawable资源分割
- dividerHeight:设置分隔条的高度
翻遍了了API发现并没有可以直接设置ListView表头或者表尾的属性,只能在Java中写代码进行设置了,可供我们调用的方法如下:
- addHeaderView(View v):添加headView(表头),括号中的参数是一个View对象
- addFooterView(View v):添加footerView(表尾),括号中的参数是一个View对象
- addHeaderView(headView, null, false):和前面的区别:设置Header是否可以被选中
- addFooterView(View,view,false):同上
对了,使用这个addHeaderView方法必须放在listview.setAdapter前面,否则会报错。
使用示例:
运行效果图:
代码实现:
先编写下表头与表尾的布局:
view_header.xml(表头),表尾一样,就不贴了:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center"> <TextView android:layout_width="match_parent" android:layout_height="48dp" android:textSize="18sp" android:text="表头" android:gravity="center" android:background="#43BBEB" android:textColor="#FFFFFF"/> </LinearLayout>
MainActivty.java:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{ private List<Animal> mData = null; private Context mContext; private AnimalAdapter mAdapter = null; private ListView list_animal; private LinearLayout ly_content; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = MainActivity.this; list_animal = (ListView) findViewById(R.id.list_animal); //动态加载顶部View和底部View final LayoutInflater inflater = LayoutInflater.from(this); View headView = inflater.inflate(R.layout.view_header, null, false); View footView = inflater.inflate(R.layout.view_footer, null, false); mData = new LinkedList<Animal>(); mData.add(new Animal("狗说", "你是狗么?", R.mipmap.ic_icon_dog)); mData.add(new Animal("牛说", "你是牛么?", R.mipmap.ic_icon_cow)); mData.add(new Animal("鸭说", "你是鸭么?", R.mipmap.ic_icon_duck)); mData.add(new Animal("鱼说", "你是鱼么?", R.mipmap.ic_icon_fish)); mData.add(new Animal("马说", "你是马么?", R.mipmap.ic_icon_horse)); mAdapter = new AnimalAdapter((LinkedList<Animal>) mData, mContext); //添加表头和表尾需要写在setAdapter方法调用之前!!! list_animal.addHeaderView(headView); list_animal.addFooterView(footView); list_animal.setAdapter(mAdapter); list_animal.setOnItemClickListener(this); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(mContext,"你点击了第" + position + "项",Toast.LENGTH_SHORT).show(); } }
好的,代码还是比较简单的,从上面我们看出来一个要注意的问题,就是:
添加表头表尾后,我们发现positon是从表头开始算的,就是你添加的第一个数据本来的 postion 是 0,但是此时却变成了 1,因为表头也算!!