导语
ListView就是一个列表显示,现在一般我都使用的都是RecyclerView,但是ListView的使用范围依然非常的广泛。
主要内容
- ListView常用技巧
- ListView常用拓展
具体内容
在Android开发中ListView是比较常用的组件,它以列表的形式展示具体内容,并且能够根据数据的长度自适应显示。
ListView常用技巧
ListView的常用技巧:
- 使用ViewHolder模式提高效率
- 设置项目间分割线
- 隐藏ListView的滚动条
- 取消ListView的Item点击效果
- 设置ListView需要显示在第几项
- 动态修改ListView
- 遍历ListView中的所有Item
- 处理空ListView
- ListView滑动监听
使用ViewHolder模式提高效率
ViewHolder模式充分利用了ListView的视图缓存机制,避免了每次在调用getView()的时候都去通过findViewById()实例化控件。据测试,使用ViewHolder将提高50%以上的效率。
public class ViewHolderAdapter extends BaseAdapter{
private List mData;
private LayoutInflater mInflater;
public ViewHolderAdapter(Context context, List mData) {
this.mData = mData;
mInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
//判断是否有缓存
if (convertView == null) {
holder = new ViewHolder();
//通过LayoutInflater实例化布局
convertView = mInflater.inflate(R.layout.viewholder_item, null);
holder.img = (ImageView) convertView.findViewById(R.id.imageView);
holder.title = (TextView) convertView.findViewById(R.id.textView);
convertView.setTag(holder);
} else {
//通过tag找到缓存的布局
holder = (ViewHolder) convertView.getTag();
}
//设置布局中控件要显示的视图
holder.img.setBackgroundResource(R.mipmap.ic_launcher);
holder.title.setText(mData.get(position));
return convertView;
}
public final class ViewHolder {
public ImageView img;
public TextView title;
}
}
设置项目间分割线
设置有颜色和有厚度的分割线。
android:dividerHeight="10dp"
android:divider="@android:color/darker_gray"
设置无分割线。
android:divider="@null"
隐藏ListView滚动条
android:scrollbars="none"
取消ListView的Item点击效果
android:listSelector="@android:color/transparent"
设置ListView需要显示在第几项
自然的滑动到第n项。
listview.setSelection(n);
瞬间的滑动到第几项
自然的滑动到第n项。
listview.smoothScrollBy(distance,duration);
listview.smoothScrollByOffset(offset);
listview.smoothScrollToPosition(index);
动态修改ListView
当数据发生变化时,可以使用notifyDataSetChanged()来刷新ListView,但是必须保证使用这个方法传进Adapter的数据List是同一个List而不能是其他对象。
mData.add("new");
mAdapter.notifyDataSetChanged();
遍历ListView中的所有Item
for (int i = 0; i < mListview.getChildCount();i++){
View view = mListview.getChildAt(i);
}
处理空ListView
在开发中,会遇到ListView为空的时候,比如:购物车在没有添加物品时,需要显示该购物车没有任何物品的View,这个时候也就是ListView数据为空的时候,ListView为我们提供好了方法。
在存在ListView的FrameLayout中,添加一个ImageView,作为空ListView时显示。
在Activity中实现ListView空数据时显示布局
ListView listView = (ListView)findViewById(R.id.listview);
listview.setEmptyView(findViewById(R.id.tv_null));
ListView滑动监听
onTouchListener:
- MotionEvent.ACTION_DOWN:触摸时操作。
- MotionEvent.ACTION_MOVE:移动时操作。
- MotionEvent.ACTION_UP:离开时操作。
mListview.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
//触摸时操作
break;
case MotionEvent.ACTION_MOVE:
//移动时操作
break;
case MotionEvent.ACTION_UP:
//离开时操作
break;
}
return false;
}
});
onScrollListener和onScroll:
- OnScrollListener.SCROLL_STATE_IDLE:滑动停止时。
- OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:正在滚动。
- OnScrollListener.SCROLL_STATE_FLING:手指抛动时。
mListview.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
switch (scrollState) {
case OnScrollListener.SCROLL_STATE_IDLE:
//滚动停止
break;
case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
//正在滚动
break;
case OnScrollListener.SCROLL_STATE_FLING:
//手指抛动时
break;
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//滚动的时候一直在调用
}
});
onScroll参数:
- firstVisibleItem:当前能看见的第一个Item的ID。
- visibleItemCount:当前能看见的Item总数。
- totalItemCount:整个ListView的Item总数。
利用onScroll方法的参数可以判断滚动到最后一行:
if(firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount>0){
//滚动到最后一行
}
判断上滑和下滑:
if(firstVisibleItem > LastVisibleItemPosition){
//上滑
}else if(firstVisibleItem < LastVisibleItemPosition){
//下滑
}
LastVisibleItemPosition = firstVisibleItem;
ListView也给我们提供封装好的方法获得当前可视的Item位置等信息:
//获取可视区域内最后一个item的id
mListview.getLastVisiblePosition();
//获取可视区域内第一个item的id
mListview.getFirstVisiblePosition();
ListView常用拓展
ListView常用拓展:
- 具有弹性的ListView
- 自动显示、隐藏布局的ListView
- 聊天ListView
- 动态改变ListView布局
具有弹性的ListView
Android默认滑动到顶部或者底部只会有一个阴影,而在5.X之后改变成了半圆的阴影。
而在IOS上,列表是具有弹性的,即滚动到顶部或者底部,会再滚动一段距离,这样的设计感觉还是挺友好的,我们也来模仿一下。
我们在查看ListView的源码的时候会发现一个控制滑动到边缘的处理方法。
@Override
protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) {
return super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent);
}
我們可以看到这样一个参数maxOverScrollY,就是他负责控制滑动的个数的,默认是0,我们重写ListView。
package com.lgl.listviewdemo;
import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.widget.ListView;
/**
* 弹性ListView
* Created by lgl on 16/3/20.
*/
public class ListViewScroll extends ListView {
private int mMaxOverdistance ;
public ListViewScroll(Context context, AttributeSet attrs) {
super(context, attrs);
//通过分辨率来调节滑动尺度
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
float density = metrics.density;
mMaxOverdistance = (int)(density*mMaxOverdistance);
}
@Override
protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) {
return super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, mMaxOverdistance, maxOverScrollY, isTouchEvent);
}
}
自动显示、隐藏布局的ListView
相信看过Google最新的应用,或者使用了MD风格的应用都知道,列表滑动的时候actionbar可以根据状态显示或者隐藏。
public class ShowAndHideListViewActivity extends AppCompatActivity {
private int mTouchSlop;
private ObjectAnimator mAnimator;
private Toolbar mToolBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_and_hide_list_view);
//添加头部
mToolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolBar);
//填充布局
ListView mListView = (ListView) findViewById(R.id.lv);
String[] str = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9"};
mListView.setAdapter(new ArrayAdapter(this, R.layout.list_item, R.id.tv, str));
//添加头布局,防止第一条数据被遮盖
View header = new View(this);
header.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
(int) getResources().getDimension(android.support.v7.
appcompat.R.dimen.abc_action_bar_default_height_material)));
mListView.addHeaderView(header);
//获得TouchSlop
mTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop();
//设置监听
mListView.setOnTouchListener(myTouchListener);
}
View.OnTouchListener myTouchListener = new View.OnTouchListener() {
public boolean mShow;
public int direction;
public float mCurrentY;
public float mFirstY;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mFirstY = event.getY();
break;
case MotionEvent.ACTION_MOVE:
mCurrentY = event.getY();
if (mCurrentY - mFirstY > mTouchSlop) {
direction = 0;//down
} else if (mFirstY - mCurrentY > mTouchSlop) {
direction = 1;//up
}
if (direction == 1) {
if (mShow) {
toolBarAnim(0);//hide
mShow = !mShow;
}
} else if (direction == 0) {
if (!mShow) {
toolBarAnim(1);//up
mShow = !mShow;
}
}
break;
case MotionEvent.ACTION_UP:
break;
}
return false;
}
};
private void toolBarAnim(int flag) {
if (mAnimator != null && mAnimator.isRunning()) {
mAnimator.cancel();
}
if (flag == 0) {
//up:hide
mAnimator = ObjectAnimator.ofFloat(mToolBar, "translationY", -mToolBar.getHeight());
} else {
//down:show
mAnimator = ObjectAnimator.ofFloat(mToolBar, "translationY", -mToolBar.getHeight(),0);
}
mAnimator.start();
}
}
布局文件的编写,记得将theme设置为NoActionBar。
聊天ListView
实现这个效果比较重要的步骤就是左右布局的填充。效果图如下。
左布局:
右布局:
聊天的实体类:
public class ChatItemListViewBean {
private int type;
private String text;
private Bitmap icon;
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Bitmap getIcon() {
return icon;
}
public void setIcon(Bitmap icon) {
this.icon = icon;
}
}
比较关键的就是Adapter的getItemViewType()方法和getViewTypeCount()方法。
public class ChatListViewAdapter extends BaseAdapter {
private List mData;
private LayoutInflater mInflater;
public ChatListViewAdapter(Context context, List mData) {
this.mData = mData;
mInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
if (getItemViewType(position) == 0) {
viewHolder = new ViewHolder();
convertView = mInflater.inflate(R.layout.left_item, null);
viewHolder.icon = (ImageView) convertView.findViewById(R.id.left_icon);
viewHolder.text = (TextView) convertView.findViewById(R.id.tv_left);
} else {
viewHolder = new ViewHolder();
convertView = mInflater.inflate(R.layout.right_item, null);
viewHolder.icon = (ImageView) convertView.findViewById(R.id.right_icon);
viewHolder.text = (TextView) convertView.findViewById(R.id.tv_right);
}
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.icon.setImageBitmap(mData.get(position).getIcon());
viewHolder.text.setText(mData.get(position).getText());
return convertView;
}
@Override
public int getItemViewType(int position) {
ChatItemListViewBean bean = mData.get(position);
return bean.getType();
}
@Override
public int getViewTypeCount() {
return 2;
}
public final class ViewHolder {
public ImageView icon;
public TextView text;
}
}
在主Activity中实现我们的效果:
public class ChatListViewActivity extends AppCompatActivity {
private ListView mListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_list_view);
mListView = (ListView) findViewById(R.id.lv_chat);
ChatItemListViewBean bean1 = new ChatItemListViewBean();
bean1.setType(0);
bean1.setIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
bean1.setText("hello how are you?");
ChatItemListViewBean bean2 = new ChatItemListViewBean();
bean2.setType(1);
bean2.setIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
bean2.setText("find thank you ,and you?");
List data = new ArrayList<>();
data.add(bean1);
data.add(bean2);
ChatListViewAdapter adapter = new ChatListViewAdapter(this, data);
mListView.setAdapter(adapter);
}
}
动态改变ListView布局
动态改变ListView布局,效果如下所示。
public class DongTaiListViewActivity extends AppCompatActivity {
private DongTaiListViewAdapter adapter;
private List list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dong_tai_list_view);
ListView listView = (ListView) findViewById(R.id.lv_dongtai);
list = new ArrayList<>();
list.add("item1");
list.add("item2");
list.add("item3");
list.add("item4");
adapter = new DongTaiListViewAdapter(this, list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
adapter.setCurrentItem(position);
adapter.notifyDataSetChanged();
}
});
}
}
public class DongTaiListViewAdapter extends BaseAdapter {
private List list;
private Context mContext;
private int mCurrentItem=0;
public DongTaiListViewAdapter(Context context, List list) {
this.list = list;
this.mContext = context;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout layout = new LinearLayout(mContext);
layout.setOrientation(LinearLayout.VERTICAL);
if (mCurrentItem == position) {
layout.addView(addFocusView(position));
} else {
layout.addView(addNormalView(position));
}
return layout;
}
private View addFocusView(int i) {
ImageView iv = new ImageView(mContext);
iv.setImageResource(R.mipmap.ic_launcher);
return iv;
}
private View addNormalView(int i) {
LinearLayout layout = new LinearLayout(mContext);
layout.setOrientation(LinearLayout.HORIZONTAL);
ImageView iv = new ImageView(mContext);
iv.setImageResource(R.mipmap.ic_launcher);
layout.addView(iv, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
TextView tv = new TextView(mContext);
tv.setText(list.get(i));
layout.addView(tv, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
layout.setGravity(Gravity.CENTER);
return layout;
}
public void setCurrentItem(int position) {
mCurrentItem = position;
}
}
更多内容戳这里(整理好的各种文集)