android开发:SwipeRefreshLayout控件仿制抖音下拉刷新效果

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_39027256/article/details/102395522

平时玩抖音可以看到我们下拉刷新的时候会有一个小圆圈在转动,效果如下图:

  

接下来介绍SwipeRefreshLayout的基本使用:

SwipeRefreshLayout和滚动条很相似,只许包含一个子布局,在xml中引入它:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/sr1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</android.support.v4.widget.SwipeRefreshLayout>

Activity代码(TextActivity)


public class TextActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
    private SwipeRefreshLayout swipeRefreshLayout;
    private ListView listView;
    private List<String> list;
    private ArrayAdapter adapter;
    private static int i = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text);
        initView();
        initData();

    }
    public void initView(){
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.sr1);
        //设置刷新圈的颜色
        swipeRefreshLayout.setColorSchemeColors(Color.GREEN);
        //设置监听
        swipeRefreshLayout.setOnRefreshListener(this);
        listView = (ListView) findViewById(R.id.lv);
    }
    public void initData(){
        //数据源
        list = new ArrayList<>();
        list.add("0");
        adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1, list);
        listView.setAdapter(adapter);
    }

    /**
     * 下拉时刷新的方法
     */
    @Override
    public void onRefresh() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(false);
                list.add(String.valueOf(i));
                //适配器刷新
                adapter.notifyDataSetChanged();
                i++;
            }
        }, 1000);
    }
}

Activity实现了SwipeRefreshLayout.OnRefreshListener接口,重写了onRefresh方法,在下拉的时候执行onRefresh()

每次刷新我们就对listView进行更新

猜你喜欢

转载自blog.csdn.net/qq_39027256/article/details/102395522