`public class MainActivity extends FragmentActivity {
/**tab容器*/
private LinearLayout ll_tab;
/**tab底部线条*/
private ImageView iv_line;
private ViewPager vp_content;
private MyFragmentPagerAdapter adapter ;
private List<Fragment> list = new ArrayList<Fragment>();
private DisplayMetrics dm;
private TranslateAnimation ta ;
/**Viewpager调用onPageSelected前所展示的选项*/
private int position = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
initView();
}
private void initView() {
vp_content = (ViewPager) findViewById(R.id.content);
iv_line = (ImageView) findViewById(R.id.line);
ll_tab = (LinearLayout) findViewById(R.id.tabs);
dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
LayoutParams lp = new LayoutParams((int)dm.widthPixels/3, (int) (2*dm.density+0.5f));
iv_line.setLayoutParams(lp);
for(int i=0;i<ll_tab.getChildCount();i++){
ll_tab.getChildAt(i).setOnClickListener(new MyOnClick(i));
}
list.add(new FristFragment());
list.add(new SecondFragment());
list.add(new FristFragment());
adapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), list);
vp_content.setAdapter(adapter);
vp_content.setOnPageChangeListener(new MyPageChange());
}
/**
* tab点击事件
*/
class MyOnClick implements OnClickListener{
private int position = -1;
public MyOnClick(int position) {
super();
this.position = position;
}
@Override
public void onClick(View v) {
vp_content.setCurrentItem(position);
}
}
class MyPageChange implements OnPageChangeListener{
@Override
public void onPageScrollStateChanged(int arg0) {
// System.out.println(“onPageScrollStateChanged”+arg0);
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// System.out.println(arg0+”===”+arg1+”===”+arg2);
}
@Override
public void onPageSelected(int item) {
//通过enable+selector改变tab背景图片
for(int i=0;i<ll_tab.getChildCount();i++){
ll_tab.getChildAt(i).setEnabled(true);
}
ll_tab.getChildAt(item).setEnabled(false);
// System.err.println(“position:”+position+”\nonPageSelected:”+item);
//dm.widthPixels*item/3==屏幕宽度总px * 当前选中项 / tab总数
ta = new TranslateAnimation(dm.widthPixels*position/3, dm.widthPixels*item/3, 0, 0);
//停留在动画结束位置
ta.setFillAfter(true);
ta.setDuration(200);
iv_line.startAnimation(ta);
position = item;
}
}
}
public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> list;
public MyFragmentPagerAdapter(FragmentManager fm,List<Fragment> list) {
super(fm);
this.list = list;
}
@Override
public Fragment getItem(int position) {
return list.get(position);
}
@Override
public int getCount() {
return list.size();
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
}
}