import android.view.MenuItem;
import android.view.View;
public class MainActivity extends Activity {
private List<View>viewList;
private ViewPager pager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
viewList = new ArrayList<View>();
View view1 = View.inflate(this, R.layout.view1, null);
View view2 = View.inflate(this, R.layout.view2, null);
View view3 = View.inflate(this, R.layout.view3, null);
View view4 = View.inflate(this, R.layout.view4, null);
viewList.add(view1);
viewList.add(view2);
viewList.add(view3);
viewList.add(view4);
//初始化ViewPager
pager = (ViewPager) findViewById(R.id.pager);
//创建PagerAdapter适配器
MyPagerAdapter adapter = new MyPagerAdapter(viewList);
//ViewPager加载适配器
pager.setAdapter(adapter);
}
@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);
}
}
package com.example.androiddemo23;
import java.util.List;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
public class MyPagerAdapter extends PagerAdapter {
private List<View>viewList;
public MyPagerAdapter(List<View>viewList){
this.viewList = viewList;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return viewList.size();
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return arg0==arg1;
}
//实例化一个页卡
@Override
public Object instantiateItem(ViewGroup container, int position) {
// TODO Auto-generated method stub
container.addView(viewList.get(position));
return viewList.get(position);
}
//销毁一个页卡
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
container.removeView(viewList.get(position));
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android:support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
</android:support.v4.view.ViewPager>
</LinearLayout>