绝大多数人,在绝大多数时候,都只能靠自己。
本讲内容:ListView下拉刷新
android中实现view的更新有两组方法,一组是invalidate,另一组是postInvalidate,其中前者是在UI线程自身中使用,而后者在非UI线程中使用。
一、ListView下拉刷新实现步骤:
1、需要添加顶部下拉加载界面
2、监听onScrollListener来判断当前是否显示在ListView的最顶部
3、因为顶部下拉加载界面是跟随手势滑动状态不断改变界面显示的,所以需要监听onTouch事件,来改变当前状态以及界面显示
4、通过接口回调的方式获取数据,然后设置界面显示刷新的数据
示例一:
下面是res/layout/activity_main.xml 布局文件:
<RelativeLayout 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" >
<com.example.listviewdemo.RefreshListView
android:id="@+id/id_listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white"
android:cacheColorHint="#00000000"
android:scrollbars="none"
android:dividerHeight="5dp" />
</RelativeLayout>
下面是res/layout/header_layout.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" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingTop="10dp" >
<LinearLayout
android:id="@+id/layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="@+id/id_tip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下拉可以刷新!" />
<TextView
android:id="@+id/id_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<ImageView
android:id="@+id/id_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/layout"
android:layout_marginRight="20dp"
android:src="@drawable/pull_to_refresh_arrow"/>
<ProgressBar
android:id="@+id/id_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/layout"
android:layout_marginRight="20dp"
android:visibility="gone"/>
</RelativeLayout>
</LinearLayout>
下面是res/layout/item_layout.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" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:orientation="horizontal" >
<ImageView
android:id="@+id/id_image"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="10dp"
android:background="@drawable/test_icon" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:id="@+id/id_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="应用程序名字"
android:textColor="@color/black"
android:textSize="18sp" />
<TextView
android:id="@+id/id_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="应用程序信息"
android:textSize="14sp" />
</LinearLayout>
<Button
android:id="@+id/id_button"
android:layout_width="60dp"
android:layout_height="40dp"
android:layout_marginRight="10dp"
android:background="@drawable/btn_selector"
android:focusable="false"
android:text="安装" />
<!-- 注意:Button会抢夺ListView的焦点,需要将Button设置为没有焦点 -->
</LinearLayout>
</LinearLayout>
下面是Entity.java文件:
//数据源 (自定义布局对应的数据)
public class Entity {
private int imageId;
private String name;
private String info;
public Entity(int imageId,String name,String info) {
this.imageId=imageId;
this.name=name;
this.info=info;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}
下面是MyBaseAdapter.java文件:
public class MyBaseAdapter extends BaseAdapter {
List<Entity> list;//保存传入的数据
LayoutInflater inflater;//布局加载器对象
Context context;
public MyBaseAdapter(Context context,List<Entity> list) {
this.list=list;
//context:使用当前的Adapter的界面对象
this.inflater=LayoutInflater.from(context);
}
/**
* 返回适配器中数据的数量
*/
public int getCount() {
return list.size();
}
/**
* 获取数据中与指定索引对应的数据项
*/
public Object getItem(int position) {
return list.get(position);
}
/**
* 获取指定行对应的ID
*/
public long getItemId(int position) {
return position;
}
/**
* 获取每一个Item的显示内容
*/
public View getView(int position, View convertView, ViewGroup parent) {
//获取指定Item
Entity entity=list.get(position);
ViewHolder holder;
//null:View未被实例化,避免了重复创建大量的convertView
if(convertView==null){
holder=new ViewHolder();
//inflate(需要加载到item中的布局文件,通常写null)
convertView=inflater.inflate(R.layout.item_layout, null);
//将控件保存在holder中
holder.image=(ImageView) convertView.findViewById(R.id.id_image);
holder.name=(TextView) convertView.findViewById(R.id.id_name);
holder.info=(TextView) convertView.findViewById(R.id.id_info);
holder.button=(Button) convertView.findViewById(R.id.id_button);
convertView.setTag(holder);//将holder与convertView关联
}else{
holder=(ViewHolder) convertView.getTag();//获取holder
}
//设置们存放在动态数组中的数据显示的内容
holder.image.setImageResource(entity.getImageId());
holder.name.setText(entity.getName());
holder.info.setText(entity.getInfo());
holder.button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
return convertView;
}
/**
* 用于对控件的实例进行缓存,避免重复调用View的findViewById()方法来获取控件的实例
*/
class ViewHolder{
private ImageView image;
private TextView name;
private TextView info;
private Button button;
}
}
下面是RefreshListView.java主界面文件:
public class RefreshListView extends ListView implements OnScrollListener{
View header;// 顶部布局文件;
int headerHeight;// 顶部布局文件的高度;
int scrollState;// listview 当前滚动状态;
int firstVisibleItem;// 当前第一个可见的item的位置;
boolean isRemark;// 标记,当前是在listview最顶端摁下的;
int startY;// 摁下时的Y值;
int state=0;// 当前的状态;
final int NONE = 0;// 正常状态;
final int PULL = 1;// 提示下拉状态;
final int RELESE = 2;// 提示释放状态;
final int REFRESHING = 3;// 刷新状态;
IRefreshListener iReflashListener;//刷新数据的接口
public RefreshListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public RefreshListView(Context context, AttributeSet attrs) {
super(context, attrs);
initViews(context);
}
public RefreshListView(Context context) {
super(context);
}
/**
* 初始化界面,添加顶部布局文件到 listview
*/
private void initViews(Context context) {
LayoutInflater inflater=LayoutInflater.from(context);
header=inflater.inflate(R.layout.header_layout, null);
header.measure(0, 0);//要加这行,不然下一行headerHeight的值获取不到的
headerHeight=header.getMeasuredHeight();
topPadding(-headerHeight);
this.addHeaderView(header);
this.setOnScrollListener(this);
}
/**
* 设置header 布局 上边距;
*/
private void topPadding(int topPadding){
//只改上边距,其余的获取其原来的
header.setPadding(header.getPaddingLeft(), topPadding, header.getPaddingRight(), header.getPaddingBottom());
header.invalidate();
}
/**
*正在滚动时回调,回调2-3次,手指没抛则回调2次。scrollState = 2的这次不回调
*回调顺序如下
*第1次:scrollState = SCROLL_STATE_TOUCH_SCROLL(1) 手指没有离开屏幕,视图正在滑动
*第2次:scrollState = SCROLL_STATE_FLING(2) 手指做了抛的动作(用户在手指离开屏幕之前,由于用力滑了一下,视图仍以靠惯性继续滑动 )
*第3次:scrollState = SCROLL_STATE_IDLE(0) 停止滚动
*/
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.scrollState=scrollState;
}
/**
* 滚动时一直回调,直到停止滚动时才停止回调。单击时回调一次。
* firstVisibleItem:当前能看见的第一个列表项ID(从0开始)
* visibleItemCount:当前能看见的列表项个数(小半个也算)
* totalItemCount:列表项共数
*/
public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
this.firstVisibleItem=firstVisibleItem;
}
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
if(firstVisibleItem==0){
isRemark=true;
startY=(int) ev.getY();
}
break;
case MotionEvent.ACTION_MOVE:
onMove(ev);
break;
case MotionEvent.ACTION_UP:
if(state==RELESE){
state=REFRESHING;
refreshViewByState();
// 加载最新数据;
iReflashListener.onRefresh();
}else if(state==PULL){
state=NONE;
isRemark=false;
refreshViewByState();
}
break;
}
return super.onTouchEvent(ev);
}
/**
* 判断移动过程操作;
* @param ev
*/
private void onMove(MotionEvent ev) {
if(!isRemark){
return;
}
int tempY=(int) ev.getY();
int space=tempY-startY;
int topPadding=space-headerHeight;
switch (state) {
case NONE:
if(space>0){
state=PULL;
refreshViewByState();
}
break;
case PULL:
topPadding(topPadding);
if(space>headerHeight+30 && scrollState==SCROLL_STATE_TOUCH_SCROLL){
state=RELESE;
refreshViewByState();
}
break;
case RELESE:
topPadding(topPadding);
if(space<headerHeight+30){
state=PULL;
refreshViewByState();
}else if(space<=0){
state=NONE;
isRemark=false;
refreshViewByState();
}
break;
}
}
/**
* 根据当前状态,改变界面显示;
*/
private void refreshViewByState(){
TextView tip=(TextView) header.findViewById(R.id.id_tip);
ImageView arrow=(ImageView) header.findViewById(R.id.id_arrow);
ProgressBar progress=(ProgressBar) header.findViewById(R.id.id_progress);
RotateAnimation anim = new RotateAnimation(0, 180,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
anim.setDuration(500);
anim.setFillAfter(true);
RotateAnimation anim1 = new RotateAnimation(180, 0,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
anim1.setDuration(500);
anim1.setFillAfter(true);
switch (state) {
case NONE:
arrow.clearAnimation();
topPadding(-headerHeight);
break;
case PULL:
arrow.setVisibility(View.VISIBLE);
progress.setVisibility(View.GONE);
tip.setText("下拉可以刷新!");
arrow.clearAnimation();
arrow.setAnimation(anim1);
break;
case RELESE:
arrow.setVisibility(View.VISIBLE);
progress.setVisibility(View.GONE);
tip.setText("松开可以刷新!");
arrow.clearAnimation();
arrow.setAnimation(anim);
break;
case REFRESHING:
topPadding(50);//正在刷新时有一个高度
arrow.setVisibility(View.GONE);
progress.setVisibility(View.VISIBLE);
tip.setText("正在刷新...");
arrow.clearAnimation();
break;
}
}
/**
* 获取完数据;
*/
public void refreshComplete(){
state=NONE;
isRemark=false;
refreshViewByState();
TextView lastupdatetime=(TextView) header.findViewById(R.id.id_time);
SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
Date date = new Date(System.currentTimeMillis());
String time = format.format(date);
lastupdatetime.setText(time);
}
/**
* 刷新数据接口
*/
public interface IRefreshListener{
public void onRefresh();
}
public void setInterface(IRefreshListener ireRefreshListener){
this.iReflashListener=ireRefreshListener;
}
}
下面是MainActivity.java主界面文件:
public class MainActivity extends Activity implements IRefreshListener{
private RefreshListView listView;
private List<Entity> lists;
MyBaseAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
listView=(RefreshListView) findViewById(R.id.id_listView);
listView.setInterface(this);
lists=getData();
adapter=new MyBaseAdapter(this, lists);
listView.setAdapter(adapter);
}
/**
* 数据源
*/
private List<Entity> getData(){
lists=new ArrayList<Entity>();
for(int i=0;i<15;i++){
Entity entity=new Entity(R.drawable.test_icon,"消灭星星","50w用户");
lists.add(entity);
}
return lists;
}
/**
* 刷新数据源
*/
private List<Entity> getRefreshData(){
for(int i=0;i<2;i++){
Entity entity=new Entity(R.drawable.test_icon,"刷新星星","50w用户");
lists.add(0,entity);
}
return lists;
}
public void onRefresh() {
Handler handler=new Handler();//延时2秒为了看效果
handler.postDelayed(new Runnable() {
public void run() {
//获取最新数据
getRefreshData();
//动态更新视图中所包含的数据
adapter.notifyDataSetChanged();
//通知listview 刷新数据完毕;
listView.refreshComplete();
}
}, 2000);
}
}
Take your time and enjoy it 要原码的、路过的、学习过的请留个言,顶个呗~~