官方下拉刷新控件SwipeRefreshLayout的使用


今天看博客,發現有了這個下拉刷新的控件,效果看上去還蠻好的,於是我也想研究的是使用一下,寫個demo。其實使用很簡單的,但就是為了能使用這個新組建我下了好久的更新,后來還是直接去官網下載最新的ADT得到解決。

該控件的完整名字是android.support.v4.widget.SwipeRefreshLayout

因此在XML文件里,必須使用這個完整的名字,另外這個類似於linearlayout,是作為整個xml文件里的根節點用的。

<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/srl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.test.MainActivity$PlaceholderFragment" >
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/tv_test"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="aaaaaaaaaaa"/>
        </ScrollView>
</android.support.v4.widget.SwipeRefreshLayout>

然后在java代碼里,只需要獲取到這個控件,給這個控件設置一個onRefreshListener即可。

public static class PlaceholderFragment extends Fragment implements OnRefreshListener {

        private SwipeRefreshLayout srl = null;
        
        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
            srl = (SwipeRefreshLayout) rootView.findViewById(R.id.srl);
            srl.setOnRefreshListener(this);
            srl.setColorScheme(android.R.color.holo_blue_bright,
                    android.R.color.holo_green_light,
                    android.R.color.holo_red_light,
                    android.R.color.holo_orange_light);
            
            return rootView;
        }

        @Override
        public void onRefresh() {
            Toast.makeText(getActivity(), "onRefresh", Toast.LENGTH_SHORT).show();
            new Thread(){

                @Override
                public void run() {
                    try {
                        sleep(3000);
                        srl.setRefreshing(false);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }    
                }
            }.start();
        }
    }

最終就可以實現一個不錯的下拉刷新的效果,非常的不錯,終於不用為寫出一個下拉刷新控件而發愁了……


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM