Android Composite(ListView)详解

原创 2016年08月30日 20:38:50
目录:
    1.ListView概述
    2.ListView使用中的重要角色(Adapter,ViewHolder,数据集,布局)
    3.ListView常用属性
    4.ListView+ArrayAdapter
    5.ListView+SimpleCursorAdapter
    6.ListView+SimpleAdapter
    7.ListView+自定义Adapter(继承BaseAdapter)
    8.下拉刷新,上拉加载(SwipeRefreshLayout(google官方下来刷新组件)+自定义上拉加载更多)
    
1.ListView概述
    见名知意,ListView即为显示list集合的一个view控件,当然他不可能直接与数据适配显示,她们之间需要adapter这个桥梁来适配
    
2.ListView使用中的重要角色(Adapter,ViewHolder,数据集,布局)
        Adapter:即为数据与布局提供桥梁进行适配,常见的Adapter有:ArrayAdapter,SimpleCursorAdapter,SimpleAdapter
            抽象的BaseAdapter。
            
        ViewHolder:ViewHolder模式其实非常优秀,他在其中扮演着优化ListView加载的效率角色(怎样优化,代码见,说起来总没那么容易理解)
        
        数据集:数据当然就不用说,就是需要显示在用户界面的一个集合,可以是图片+文字或者只有文字。
        
        布局:就是整个ListView控件和单条数据的显示样式布局,换句话说就是定义你的单个数据应该如何显示。
        
3.ListView常用属性
    android:choiceMode="multipleChoice|none|multipleChoiceModal|singleChoice":设置列表项选择模式,单选,多选或者默认的无法选择
    android:fastScrollEnabled="true":设置是否开启快速滚动条
    android:fastScrollAlwaysVisible="true":设置是否总是显示快速滚动条
    android:scrollbars="horizontal|vertical|none":设置滚动条,竖直,水平,无
    android:stackFromBottom="true|false":设置是否从底部开始显示
    android:transcriptMode="alwaysScroll|normal|disabled":设置ListView在增加新项时是否自动滑动到底部
    android:divider="":设置item之间的分割(图片,颜色,@null都可以)
    android:fadingEdgeLength="":设置item阴影
    android:listSelector="":设置列表选中项的背景图片
    android:drawSelectorOnTop="true|false":设置选中项的背景是否显示在选择内容之上


4.ListView+ArrayAdapter
    4.1)主java类MainActivity.java
    
package com.example.listview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private ListView listView;
    private ArrayList<String> list;
    private ArrayAdapter<String> arrayAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化布局
        listView = (ListView) findViewById(R.id.first_lv);
        //设置不滑动时是否显示滑动条,true表示当滑动时显示,不滑动时不显示,false一直显示
        //listView.setScrollbarFadingEnabled(false);
        //设置垂直ScrollBar是否开启,不开启在滑动的时候不显示ScrollBar
        listView.setVerticalScrollBarEnabled(false);
        //初始化数据
        list = new ArrayList<String>();
        for (int i= 1;i<20;i++){
            list.add("数据"+i);
        }
        //初始化适配器
        //Context:表示当前context及MainActivity.this
        // int resource:单条数据显示布局
        // List<T> objects:ArrayList数据集合
        arrayAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,list);
        //设置适配器
        listView.setAdapter(arrayAdapter);
    }

} 

  
    4.2)主布局文件activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.listview.MainActivity">
    <!--
    android:choiceMode="multipleChoice|none|multipleChoiceModal|singleChoice":设置列表项选择模式,单选,多选或者默认的无法选择
    android:fastScrollEnabled="true":设置是否开启快速滚动条
    android:fastScrollAlwaysVisible="true":设置是否总是显示快速滚动条
    android:scrollbars="horizontal|vertical|none":设置滚动条,竖直,水平,无
    android:stackFromBottom="true|false":设置是否从底部开始显示
    android:transcriptMode="alwaysScroll|normal|disabled":设置ListView在增加新项时是否自动滑动到底部
    android:divider="":设置item之间的分割(图片,颜色,@null都可以)
    android:fadingEdgeLength="":设置item阴影
    android:listSelector="":设置列表选中项的背景图片
    android:drawSelectorOnTop="true|false":设置选中项的背景是否显示在选择内容之上
    -->
<ListView
    android:id="@+id/first_lv"
    android:transcriptMode="disabled"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

</ListView>
</RelativeLayout>

 
    4.3)效果截图

5.ListView+SimpleCursorAdapter(读取显示联系人)

    ps:我们暂不深究如何对手机联系人进行增删改查操作,只是简单使用它来实现ListView+SimpleCursorAdapter的使用
    
    5.1)主java类SimpleCursorAdapterActivity.java
    
package com.example.listview;

import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;

/**
 * Created by elimy on 2016-08-25.
 */
public class SimpleCursorAdapterActivity extends AppCompatActivity {
    private ListView simpleCursorListView;
    private SimpleCursorAdapter simpleCursorAdapter;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simple_cursor_activity);
        //初始化ListView控件
        simpleCursorListView = (ListView) findViewById(R.id.simple_cursor_lv);
        //实例化内容接收者
        ContentResolver resolver = getContentResolver();
        //此处访问查询联系人的方法和ContactsContract.Contacts.CONTENT_URI效果相同
/*        Uri uri=Uri.parse("content://com.android.contacts/contacts");
        Cursor cursor =resolver.query(uri,null,null,null,null);*/
        //通过内容接收者去查询数据,返回Cursor数据集
        //注意:People.CONTENT_URI被ContactsContract.Contacts.CONTENT_URI替代
        Cursor cursor =resolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

        if(cursor==null){
            Log.d("cursor","cursor is null");
        }
        //实例化simpleCursorAdapter
       /* Context:表示当前的Context即SimpleCursorAdapterActivity.this,
        layout:单条数据的布局文件ID,
        Cursor:数据库查询返回的数据集,
        from:数据集需要显示的的字段,
        to:布局文件中与显示字段对应的资源ID,
        flags:定义该adapter的行为
        */
        simpleCursorAdapter = new SimpleCursorAdapter(this,R.layout.simple_cursor_item,
               cursor,new String[]{ContactsContract.Contacts.DISPLAY_NAME,ContactsContract.Contacts.NAME_RAW_CONTACT_ID},new int[]{R.id.call_name,R.id.call_number},0);
        //设置适配器到ListView
        simpleCursorListView.setAdapter(simpleCursorAdapter);
/*        while (cursor.moveToNext()){
            String name =cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            Log.d("contact name:",name);
        }*/
    }
}   

  
    5.2)主布局xml文件simple_cursor_activity.xml
    
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
<ListView
    android:id="@+id/simple_cursor_lv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

</ListView>
</RelativeLayout>    


    5.3)单个item xml文件simple_cursor_item.xml
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_marginBottom="10dp"
    android:layout_marginTop="10dp"
    android:layout_height="match_parent">
<TextView
    android:id="@+id/call_name"
    android:textSize="24sp"
    android:text="name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
    <TextView
        android:gravity="center"
        android:textSize="18sp"
        android:layout_marginLeft="10dp"
        android:id="@+id/call_number"
        android:text="number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout> 
 
    注意:访问联系人需要注册权限:<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
    
    5.4)效果截图

6.ListView+SimpleAdapter
        6.1)主java类SimpleAdapterDemo.java
package com.example.listview;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by elimy on 2016-08-28.
 */
public class SimpleAdapterDemo extends AppCompatActivity {
    private ArrayList<Map<String,Object>> myList;
    private HashMap<String,Object> myMap;
    private ListView simpleAdapterListView;
    private SimpleAdapter simpleAdapter;
    private ImageView icon;
    private TextView name_tv,desc_tv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simple_adpter);
       //初始化ListView
        simpleAdapterListView = (ListView) findViewById(R.id.simple_adapter_lv);
        //初始化simpleAdapter
        simpleAdapter = new SimpleAdapter(this,getMyList(),
        R.layout.simple_adapter_item,new String[]{"icon","name","desc"},
                new int[]{R.id.icon,R.id.name,R.id.desc});
        //设置适配器
        simpleAdapterListView.setAdapter(simpleAdapter);


    }
    /*
    * 封装方法初始化数据
    * */
    public ArrayList<Map<String,Object>> getMyList(){
        //实例化带泛型ArrayList
        myList =new ArrayList<Map<String, Object>>();
        //初始化HashMap
        myMap = new HashMap<String,Object>();
        //放入数据,这里就直接put,如果有数据库读取数据可以将cursor类型数据转换成map类型
        myMap.put("icon",R.drawable.a2);
        myMap.put("name","支付宝");
        myMap.put("desc","支付宝支付为大家!");
        myList.add(myMap);
        //第二条数据
        myMap = new HashMap<String,Object>();
        myMap.put("icon",R.drawable.a3);
        myMap.put("name","google浏览器");
        myMap.put("desc","想看啥看啥!");
        myList.add(myMap);
        //第三条数据
        myMap = new HashMap<String,Object>();
        myMap.put("icon",R.drawable.a7);
        myMap.put("name","米聊");
        myMap.put("desc","和女神面对面!");
        myList.add(myMap);
        //第四条数据
        myMap = new HashMap<String,Object>();
        myMap.put("icon",R.drawable.a8);
        myMap.put("name","指南针");
        myMap.put("desc","想去哪儿,就去哪儿!");
        myList.add(myMap);
        //第五条数据
        myMap = new HashMap<String,Object>();
        myMap.put("icon",R.drawable.a9);
        myMap.put("name","时钟");
        myMap.put("desc","时时刻刻,每分每秒都为你计算!");
        myList.add(myMap);
        return myList;
    }
}

     
        6.2)主布局simple_adapter.xml
        
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ListView
        android:id="@+id/simple_adapter_lv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </ListView>
</RelativeLayout>

      
        6.3)单个item xml布局simple_adapter_item.xml
 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="85dp"
        android:layout_height="85dp"
        android:src="@drawable/a2"
        android:id="@+id/icon" />
    <RelativeLayout
        android:layout_alignBaseline="@+id/icon"
        android:layout_toRightOf="@+id/icon"
        android:id="@+id/tv_rLayout"
        android:orientation="vertical"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Large Text"
            android:id="@+id/name" />

        <TextView
            android:layout_marginTop="10dp"
            android:layout_below="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Medium Text"
            android:id="@+id/desc"
            android:singleLine="true"
            android:ellipsize="end"
            />

    </RelativeLayout>

</RelativeLayout>
           
        6.4)效果截图
        
7.ListView+自定义Adapter(继承BaseAdapter)

    ps:有时候我们不仅仅是显示数据,可能会在单个item中添加一些控件并实现控件的相关操作,比如添加:button,checkbox等
    
    7.1)自定义Adapter类CustomAdapter.java
    
package com.example.listview;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Map;

/**
 * Created by elimy on 2016-08-28.
 */
public class CustomAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<Map<String,Object>> list;
    private LayoutInflater inflater;
    /*
    * 带参数构造方法
    * Context:指实例化CustomAdapter的上下文
    * ArrayList:表示需要适配的数据源
    * */
    public CustomAdapter(Context context, ArrayList<Map<String, Object>> list) {
        //记得初始化布局加载器
        this.inflater =LayoutInflater.from(context);
        this.context =context;
        this.list = list;
    }

    @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(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder=null;
        if (holder==null){
           holder=new ViewHolder();
            if(convertView == null){
                //适配并绑定单个item的显示布局
                convertView = inflater.inflate(R.layout.custom_adapter_item,null);

            }
            //如果ViewHolder映射关系不存在,则构造映射关系,如果存在直接复用
            holder.icon = (ImageView) convertView.findViewById(R.id.custom_icon);
            holder.name = (TextView) convertView.findViewById(R.id.name);
            holder.desc = (TextView) convertView.findViewById(R.id.desc);
            holder.download = (Button) convertView.findViewById(R.id.download);
            convertView.setTag(holder);

        }else {
            //取出ViewHolder复用
            holder = (ViewHolder) convertView.getTag();
        }
        //从list中设置图标到布局显示
        holder.icon.setBackgroundResource((Integer) list.get(position).get("icon"));
        Integer res =(Integer) list.get(position).get("icon");
        Log.d("icon",res.toString());
        //设置name到布局显示
        holder.name.setText((String) list.get(position).get("name"));
        //设置描述到布局显示
        holder.desc.setText((String) list.get(position).get("desc"));
        //设置button监听
        holder.download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewHolder holder = new ViewHolder();
                Log.d("click_debug",list.get(position).get("name")+"开始下载");
                Toast.makeText(context,list.get(position).get("name")+"开始下载",Toast.LENGTH_SHORT).show();
            }
        });
        return convertView;
    }

    /**
    *保存布局控件,方便后面复用以此提高加载效率
    * */
    class ViewHolder{
        private ImageView icon;
        private TextView name,desc;
        private Button download;
    }
}

 
    7.2)主布局java类BaseAdapterActivity.java
package com.example.listview;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by elimy on 2016-08-28.
 */
public class BaseAdapterActivity extends AppCompatActivity {
    private ListView customAdapterListView;
    private CustomAdapter customAdapter;
    private ArrayList<Map<String,Object>> myList;
    private Map<String,Object> myMap;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_adapter);
        //初始化ListView控件
        customAdapterListView = (ListView) findViewById(R.id.custom_adapter_lv);
        //获取数据
        ArrayList<Map<String,Object>> list =getMyList();
        //实例化自定义适配器
        customAdapter = new CustomAdapter(BaseAdapterActivity.this,list);
        //设置适配器
        customAdapterListView.setAdapter(customAdapter);
    }
    /*
    * 封装方法初始化数据
    * */
    public ArrayList<Map<String,Object>> getMyList(){
        //实例化带泛型ArrayList
        myList =new ArrayList<Map<String, Object>>();
        //初始化HashMap
        myMap = new HashMap<String,Object>();
        //放入数据,这里就直接put,如果有数据库读取数据可以将cursor类型数据转换成map类型
        myMap.put("icon",R.drawable.a2);
        myMap.put("name","支付宝");
        myMap.put("desc","支付宝支付为大家!");
        myList.add(myMap);
        //第二条数据
        myMap = new HashMap<String,Object>();
        myMap.put("icon",R.drawable.a3);
        myMap.put("name","google浏览器");
        myMap.put("desc","想看啥看啥!");
        myList.add(myMap);
        //第三条数据
        myMap = new HashMap<String,Object>();
        myMap.put("icon",R.drawable.a7);
        myMap.put("name","米聊");
        myMap.put("desc","和女神面对面!");
        myList.add(myMap);
        //第四条数据
        myMap = new HashMap<String,Object>();
        myMap.put("icon",R.drawable.a8);
        myMap.put("name","指南针");
        myMap.put("desc","想去哪儿,就去哪儿!");
        myList.add(myMap);
        //第五条数据
        myMap = new HashMap<String,Object>();
        myMap.put("icon",R.drawable.a9);
        myMap.put("name","时钟");
        myMap.put("desc","时时刻刻,每分每秒都为你计算!");
        myList.add(myMap);
        return myList;
    }
} 

  
    7.3)主布局xml文件custom_adapter.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
<ListView
    android:id="@+id/custom_adapter_lv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

</ListView>
</LinearLayout>   

 
    7.4)单个item布局文件custom_adapter_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="85dp"
        android:layout_height="85dp"
        android:id="@+id/custom_icon" />
    <RelativeLayout
        android:layout_alignBaseline="@+id/custom_icon"
        android:layout_toRightOf="@+id/custom_icon"
        android:id="@+id/tv_rLayout"
        android:orientation="vertical"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Large Text"
            android:id="@+id/name" />

        <TextView
            android:layout_marginTop="10dp"
            android:layout_below="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Medium Text"
            android:id="@+id/desc"
            android:singleLine="true"
            android:ellipsize="end"
            />

    </RelativeLayout>
    <Button
        android:layout_marginTop="10dp"
        android:layout_marginRight="10dp"
        android:layout_alignParentRight="true"
        android:id="@+id/download"
        android:text="下载"
        android:textColor="#fff"
        android:textSize="14sp"
        android:background="@color/colorAccent"
        android:layout_width="60dp"
        android:layout_height="30dp" />

</RelativeLayout> 

     
    7.5)效果截图
    
8.下拉刷新,上拉加载(SwipeRefreshLayout(google官方下来刷新组件)+自定义上拉加载更多)
    8.1)自定义ListView类PullRefreshListView.java
package com.example.listview;

import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;

/**
 * Created by elimy on 2016-08-29.
 */
public class PullRefreshListView extends ListView implements AbsListView.OnScrollListener{

    //底部加载更多的控件
    private View footerView;
    //底部刷新高度
    private int footerHeight;
    //标识是否滑动到底部
    private boolean isScrollToBottom = false;
    //标识是否正在加载
    private boolean isRefreshing = false;
    //对ListView的下拉和上拉刷新进行监听的变量
    private OnRefreshListener myOnRefreshListener;

    /*
    带一个参数的构造函数
    * */
    public PullRefreshListView(Context context) {
        super(context);
    }
    /*
    * 带两个参数的构造函数
    * */
    public PullRefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //通过View.inflate()初始化自定义的底部刷新View
            footerView = View.inflate(getContext(),R.layout.footer_view,null);
            Log.d("footer_view",footerView.toString()+"");
        //测绘footerView
        if (footerView != null){
            footerView.measure(0,0);
            //获取底部控件高度并初始化
            footerHeight = footerView.getMeasuredHeight();
            //刚开始隐藏footerView
            footerView.setPadding(0, -footerHeight, 0, 0);
            //添加footerView到ListView
            this.addFooterView(footerView);
            //为初始化的PullRefreshListView设置监听
            this.setOnScrollListener(this);
        }else {
            Log.d("footerView_debug","footerView is null");
        }

    }
    /*
    * 开放监听器接口,方便在使用的时候为自定义的PullRefreshListView添加监听并实现监听后的操作
    * */
    public void setOnRefreshListener(OnRefreshListener onRefreshListener){
        myOnRefreshListener =onRefreshListener;
    }
    /*
    * 实现隐藏方法,提供给使用的类在加载完后隐藏footerView
    * */
    public void hideFooterView (){
        footerView.setPadding(0, -footerHeight, 0, 0);
        isRefreshing=false;
    }
    /*
    *scroll状态改变的监听,继承至AbsListView.OnScrollListener
    * */
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (scrollState == SCROLL_STATE_FLING || scrollState == SCROLL_STATE_IDLE){
            if (!isRefreshing && isScrollToBottom){
              isRefreshing = true;
                //显示出footerView
                footerView.setPadding(0,0,0,0);
                //设置选中可见item的最后一项
                this.setSelection(this.getCount());
                if (myOnRefreshListener != null){
                    myOnRefreshListener.refreshData();
                }
            }
        }
    }
    /*
    * 对ListView正在滚动进行监听
    * */
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        int endItemPosition =totalItemCount-1;
        if (endItemPosition==getLastVisiblePosition()){
            isScrollToBottom =true;
        }else {
            isScrollToBottom = false;
        }
    }
    /*
    * 自定义一个接口供外界调用实现上拉刷新数据
    * */
    public interface OnRefreshListener{
        void refreshData();
    }
}

  
    8.2)底部刷新view xml布局footer_view.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    xmlns:android="http://schemas.android.com/apk/res/android" >

    <RelativeLayout
        android:paddingBottom="10dp"
        android:paddingTop="10dp"
       android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <ProgressBar
        android:layout_toLeftOf="@+id/refresh_tv"
        android:id="@+id/refresh_pgbar"
        android:layout_marginTop="5dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyleSmall" />
        <TextView

            android:id="@+id/refresh_tv"
            android:text="正在加载数据..."
            android:textSize="20dp"
            android:gravity="center"
            android:layout_centerHorizontal="true"
            android:layout_alignBaseline="@+id/refresh_pgbar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </RelativeLayout>
</LinearLayout>

 
    8.3)主activity类PullRefreshActivity.java
 
package com.example.listview;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;

import java.util.ArrayList;



/**
 * Created by elimy on 2016-08-29.
 */
public class PullRefreshActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener,PullRefreshListView.OnRefreshListener {
    private SwipeRefreshLayout swipeRefreshLayout;
    private PullRefreshListView pullRefreshListView;
    private ArrayAdapter myAdapter;
    private ListItems listItems;
    private  ArrayList<String> firstItems;
    //标识下拉是否正在刷新
    private boolean isRefresh = false;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.refresh_listview);
        //初始化控件
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
        pullRefreshListView = (PullRefreshListView) findViewById(R.id.custom_refresh_lv);
        //设置监听器
        swipeRefreshLayout.setOnRefreshListener(this);
        pullRefreshListView.setOnRefreshListener(this);
        //初始化数据类
        listItems = new ListItems();
        firstItems = listItems.getFirstData();
        myAdapter = new ArrayAdapter(this,android.R.layout.simple_expandable_list_item_1,firstItems);
        pullRefreshListView.setAdapter(myAdapter);


        //设置圆圈进度条的背景颜色
       swipeRefreshLayout.setProgressBackgroundColorSchemeColor(
                getResources().getColor(R.color.white));

        //设置进度条变化的颜色
        swipeRefreshLayout.setColorSchemeResources(
                R.color.colorAccent,
                R.color.purple
                );
        //设置加载圆圈大小
        swipeRefreshLayout.setSize(SwipeRefreshLayout.LARGE);
        //设置下拉多少距离开始触发刷新
        swipeRefreshLayout.setDistanceToTriggerSync(200);

    }

    /*
        * 继承自定义的PullRefreshListView的内部接口OnRefreshListener
        * 实现上拉加载数据的操作
        *
        * */
    @Override
    public void refreshData() {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                ArrayList<String> bottomData = listItems.getBottomRefreshData();
                firstItems.addAll(bottomData);
                //通知数据改变
                myAdapter.notifyDataSetChanged();
                //隐藏footerView,停止更新
                pullRefreshListView.hideFooterView();
            }
        },5000);

    }
    /*
    * 继承SwipeRefreshLayout.OnRefreshListener的方法
    * 实现下拉刷新操作
    * */
    @Override
    public void onRefresh() {
        if (!isRefresh)
        {
            isRefresh =true;
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ArrayList<String> startData = listItems.getStartData();
                    firstItems.addAll(0,startData);
                    //通知数据改变
                    myAdapter.notifyDataSetChanged();
                    isRefresh =false;
                    //设置隐藏或者显示刷新进度圆圈
                    swipeRefreshLayout.setRefreshing(false);
                }
            },5000);
        }
    }
}  

   
    8.4)主布局文件refresh_listview.xml  
 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.example.listview.PullRefreshListView
            android:id="@+id/custom_refresh_lv"
          android:layout_width="match_parent"
          android:layout_height="match_parent">

      </com.example.listview.PullRefreshListView>
    </android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>

   
    8.5)数据构造类ListItems.java
package com.example.listview;

import java.util.ArrayList;

/**
 * Created by elimy on 2016-08-29.
 */
public class ListItems {
    public ArrayList<String> getBottomRefreshData(){
       ArrayList<String> list = new ArrayList<String>();
        for (int i = 1;i<=5;i++){
            list.add("上拉刷新数据"+i);
        }
        return list;
    }
    public ArrayList<String> getFirstData(){
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 1;i<=5;i++){
            list.add("初始数据"+i);
        }
        return list;
    }
    public ArrayList<String> getStartData(){
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 1;i<=5;i++){
            list.add("下拉刷新数据"+i);
        }
        return list;
    }
}

 
    8.6)效果截图
        依次为没做操作效果,下拉刷新中效果,上拉加载更多中效果(不会做gif动图真是淡疼)

       


  推荐文章:
             http://www.lai18.com/content/3281354.html
             http://www.jianshu.com/p/97ab87cfce47
             https://github.com/android-cjj/BeautifulRefreshLayout

版权声明:欢迎分享,但请注明出处,谢谢

相关文章推荐

Android Composite(Dialog)详解

目录:     1.Dialog概述     2.Dialog中的重要角色     3.常见几种类型的Dialog简单使用         3...

Android Composite(Menu)详解

目录:     1.Menu概述     2.Menu的一些常用属性     3.Menu分类         3.1 选项菜单(Option...

android ListView 详解

  • 2011-12-26 14:27
  • 184KB
  • 下载

android ListView详解

  • 2011-09-13 09:28
  • 388KB
  • 下载

Android-Composite

Android-Composite   一 ListView 加载方式1: 直接从xml中加载元素数组,在listview中设置android:entries="@array/string_a...

android开发:listview详解

  • 2011-01-13 22:07
  • 352KB
  • 下载

android UI体系中的Composite模式

Java深入到一定程度,就不可避免的碰到设计模式这一概念,了解设计模式,将使自己对java中的接口或抽象类应用有更深的理解.设计模式在java的中型系统中应用广泛,遵循一定的编程模式,才能使自己的代码...

android设计模式之Composite

今天我们来谈谈android的设计模式的Composite吧,里面的例子用的是高焕堂老师的一些资料,加上自己对android的一些理解,先说说具体的本文的代码的框架的结构吧,首先有一个叫Money的类...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)