package com.xiaoke.freash;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity implements OnClickListener {
// 数据作为全局变量
private ArrayList<String> list = null;
private int index = 0;
private ArrayAdapter adapter = null;
private SwipeRefreshLayout swipere = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = new ArrayList<String>();
// 通过布局文件获取下拉对象
swipere = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
// 通过布局文件获取listview对象
ListView lv = (ListView) findViewById(R.id.listView);
// 获取button
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(this);
// list.add("0");
// 下拉框的样式设计
swipere.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_orange_light,
android.R.color.holo_green_light);
// 下拉监听事件
swipere.setOnRefreshListener(new OnRefreshListener() {
// 下拉或调用该方法
@Override
public void onRefresh() {
// TODO Auto-generated method stub
longTimeOperation();
}
});
// listview布局的样式
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,
list);
// 添加进listview中
lv.setAdapter(adapter);
}
// 点击添加选项
@Override
public void onClick(View v) {
index++;
list.add(0, index + "");
}
private void longTimeOperation() {
// true,刷新开始,所以启动刷新的UI样式.
swipere.setRefreshing(true);
// 开始启动刷新...
// 在这儿放耗时操作的 AsyncTask线程、后台Service等代码。
// add(0,xxx)每次将更新的数据xxx添加到头部。
//list.add(0, "" + index++);
adapter.notifyDataSetChanged();
// 刷新完毕.
// false,刷新完成,因此停止UI的刷新表现样式。
swipere.setRefreshing(false);
}
}
布局代码
<LinearLayout 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:orientation="vertical" >
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="5">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</android.support.v4.widget.SwipeRefreshLayout>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="添加消息" />
</LinearLayout>