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

时间:2023-03-10 04:07:26
官方下拉刷新控件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();
}
}

最终就可以实现一个不错的下拉刷新的效果,非常的不错,终于不用为写出一个下拉刷新控件而发愁了……