废话不多说,效果如图:
代码如下:
page.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="@+id/page"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/forward"
android:text="上一页"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/backward"
android:text="下一页"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
</LinearLayout>
JAVA代码:
public class PageListView extends Activity {
private ListView lv ;
private List mData ;
private Button forward , backward;
private int index = 0 ; //分页索引
private int viewCount = 5 ; //每页显示5条
PageAdapter mPageAdapter ;
@Override
protected void onCreate(Bundle b){
super.onCreate(b);
setContentView(R.layout.page);
lv = (ListView) findViewById(R.id.page);
mData = getData();
mPageAdapter = new PageAdapter(this);
lv.setAdapter(mPageAdapter);
forward = (Button) findViewById(R.id.forward);
backward = (Button) findViewById(R.id.backward);
forward.setOnClickListener(listener);
backward.setOnClickListener(listener);
checkButton();//初始化没有上一页
}
private View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.forward:
to_Forward();
break;
case R.id.backward:
to_Backward();
break;
}
}
};
/**
* 上一页
*/
private void to_Forward() {
index -- ;
mPageAdapter.notifyDataSetChanged();
checkButton();
}
/**
* 下一页
*/
private void to_Backward() {
index ++ ;
mPageAdapter.notifyDataSetChanged();
checkButton();
}
private void checkButton(){
if(index <= 0){
forward.setEnabled(false);
}else if(mData.size()-index*viewCount <= viewCount ){
backward.setEnabled(false);
}else{
forward.setEnabled(true);
backward.setEnabled(true);
}
}
private List getData(){
List list = new ArrayList();
for (int i = 0; i < 17; i++) {
list.add(i);
}
return list;
}
class PageAdapter extends BaseAdapter{
private Context mContext ;
public PageAdapter(Context context){
this.mContext = context ;
}
@Override
public int getCount() {
int temp = index * viewCount ;
if((mData.size() - temp) < viewCount){
return (mData.size()-temp);
}else{
return viewCount;
}
}
@Override
public Object getItem(int position) {
return position ;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv = new TextView(mContext);
tv.setGravity(Gravity.CENTER);
tv.setText(mData.get(position+index*viewCount)+"");
return tv;
}
}
}