package com.example.day8viewpager;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
private Button button1;
private Button button2;
private Button button3;
private ViewPager viewpager;
private List<View> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//设置假数据,viewPager每个item要显示的内容
setData();
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
viewpager = (ViewPager) findViewById(R.id.viewpager);
// 设置适配器;
viewpager.setAdapter(new MyPagerAdapter(list));
//设置viewPager默认第一次进来时显示的view;
viewpager.setCurrentItem(0);
//首次加载viewPager 页面对应的button的文字颜色
setButtonColor(viewpager.getCurrentItem());
//viewPager的页面改变监听
viewpager.setOnPageChangeListener(new OnPageChangeListener() {
//viewPager当前显示的view
@Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
setButtonColor(arg0);
}
//viewPager滑动移动距离,和显示的view;参数一:要显示的view,参数二:滑动的偏移量;参数三:滑动的像素
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
//当前页面的改变状态
//停止状态 SCROLL_STATE_IDLE 0
//拖拽状态 SCROLL_STATE_DRAGGING 1
//固定状态 SCROLL_STATE_SETTLING 2
@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
/**
* 设置button的颜色
* @param i viewPager当前页面对应的position
*/
private void setButtonColor(int currentItem) {
// TODO Auto-generated method stub
switch (currentItem) {
case 0:
button1.setTextColor(Color.WHITE);
button2.setTextColor(Color.BLACK);
button3.setTextColor(Color.BLACK);
break;
case 1:
button2.setTextColor(Color.WHITE);
button1.setTextColor(Color.BLACK);
button3.setTextColor(Color.BLACK);
break;
case 2:
button3.setTextColor(Color.WHITE);
button1.setTextColor(Color.BLACK);
button2.setTextColor(Color.BLACK);
break;
}
}
/**
* 设置假数据,viewPager每个item要显示的内容
*/
private void setData() {
list = new ArrayList<View>();
View view1=View.inflate(MainActivity.this, R.layout.one, null);
View view2=View.inflate(MainActivity.this, R.layout.two, null);
View view3=View.inflate(MainActivity.this, R.layout.three, null);
list.add(view1);
list.add(view2);
list.add(view3);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
viewpager.setCurrentItem(0);
break;
case R.id.button2:
viewpager.setCurrentItem(1);
break;
case R.id.button3:
viewpager.setCurrentItem(2);
break;
}
}
}