在这里写了一个很简单的demo,用于巩固它的用法。实际项目中,是有差别的。
<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"
tools:context="com.example.vpidemo.MainActivity" >
<com.viewpagerindicator.TabPageIndicator
android:id="@+id/vpi"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<android.support.v4.view.ViewPager
android:id="@+id/vp"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
</LinearLayout>
@ViewInject(R.id.vp)
ViewPager vp;
@ViewInject(R.id.vpi)
TabPageIndicator pi;
String [] Titles={"关注","热点","美文","测试"};
PagerAdapter mTableAdapter= new PagerAdapter() {
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return arg0==arg1;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return Titles.length;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
//super.destroyItem(container, position, object);
container.removeView((View)object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
TextView tv= new TextView(container.getContext());
tv.setText(Titles[position%Titles.length]);
container.addView(tv);
return tv;
}
@Override
public CharSequence getPageTitle(int position) {
// TODO Auto-generated method stub
return Titles[position%Titles.length];
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewUtils.inject(this);
vp.setAdapter(mTableAdapter);
pi.setViewPager(vp,0);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
viewpager的监听是在pi上面设置的。一般在使用中会定制化相关的修改,但是一般而言只需要更改样式就可以达到目的。不用操作代码。