有时候使用ListView显示一些数据时,希望在列表项的尾部增加一个页脚(注:不是放在屏幕的最低端),页脚会随着ListView的数量的增加而自动跟随,由于ListView在数量超过屏幕显示的数量的时候,导致你使用在布局中layout_below某个布局下失效(如果ListView数量少于屏幕显示数量,则显示页脚,否则将被覆盖)。
实现方式有两种,一种是通过ScrollView里面嵌套布局实现,另一种是通过ListView的addFooterView()方法实现,第一种google官方不推荐。
listview的脚标布局文件listview_friend_footer.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv_friend_footer"
android:layout_width="match_parent"
android:layout_height="48dp"
android:gravity="center"
android:textSize="14sp"
android:textColor="#000000"/>
</LinearLayout>
界面布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/background"
android:orientation="vertical"
tools:context="com.sdlj.vehiclerepair.activity.FriendActivity">
<ListView
android:id="@+id/lv_friend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="@color/background"
android:dividerHeight="@dimen/friend_list_divider_height"
android:scrollbars="none"/>
</LinearLayout>
Activity java代码
public class FriendActivity extends AppCompatActivity {
private ListView listView;
private FriendListAdapter adapter;//自定义adapter
private ArrayList arrayList;
private HashMap hashMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_friend);
initView();
}
//初始换布局控件
private void initView() {
listView = (ListView)findViewById(R.id.lv_friend);
arrayList = new ArrayList();
for(int i=0;i<15;i++){
hashMap = new HashMap();
hashMap.put("image",R.mipmap.ic_launcher);
hashMap.put("title",R.string.app_name);
arrayList.add(hashMap);
}
if(adapter==null){
adapter = new FriendListAdapter(this,arrayList);
}else {
//刷新适配器,不用每次都new SongAdapter(this,songArrayList)
adapter.notifyDataSetChanged();
}
//为listview设置脚标
View footerView = ((LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listview_friend_footer, null, false);
TextView tvTotal = (TextView)footerView.findViewById(R.id.tv_friend_footer);
tvTotal.setText(String.format(getResources().getString(R.string.friend_total),arrayList.size()));
listView.addFooterView(footerView);
listView.setAdapter(adapter);
}
}
主要是通过LayoutInflater加载一个View并添加到ListView上即可。
注意:setFooterView方法必须在setAdapter方法前设置,否则不显示footer