ViewPager和FragmentTabHost的使用

来源:互联网 发布:python mac 桌面路径 编辑:程序博客网 时间:2024/05/17 03:50

1、示例1,展示ViewPager和FragmentTabHost的用法

1)写3个Fragment的布局文件,供Fragment引用

fragment_first.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    xmlns:android="http://schemas.android.com/apk/res/android">    <TextView         android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:text="First"        android:textSize="30sp"/></RelativeLayout>
fragment_second.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    xmlns:android="http://schemas.android.com/apk/res/android">    <TextView         android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:text="Second"        android:textSize="30sp"/></RelativeLayout>
fragment_third.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    xmlns:android="http://schemas.android.com/apk/res/android">    <TextView         android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:text="Third"        android:textSize="30sp"/></RelativeLayout>

2)写3个Fragment类,展示用于切换的内容

FirstFragment.java

public class FirstFragment extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {return inflater.inflate(R.layout.fragment_first, container, false);}}

SecondFragment.java

public class SecondFragment extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {return inflater.inflate(R.layout.fragment_second, container, false);}}

ThirdFragment.java

public class ThirdFragment extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {return inflater.inflate(R.layout.fragment_third, container, false);}}

3)写ViewPager的布局文件

activity_main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    xmlns:android="http://schemas.android.com/apk/res/android">    <android.support.v4.view.ViewPager        android:id="@+id/viewPager"        android:layout_width="match_parent"        android:layout_height="match_parent"/></LinearLayout>

4)写ViewPager对应的FragmentActivity

public class MainActivity extends FragmentActivity {private ViewPager mViewPager;@Overrideprotected void onCreate(Bundle arg0) {super.onCreate(arg0);setContentView(R.layout.activity_main);mViewPager = (ViewPager) findViewById(R.id.viewPager);List<Class<? extends Fragment>> list = new LinkedList<Class<? extends Fragment>>();list.add(FirstFragment.class);list.add(SecondFragment.class);list.add(ThirdFragment.class);mViewPager.setAdapter(new MyAdapter(list));}private class MyAdapter extends FragmentPagerAdapter{List<Class<? extends Fragment>> mList;public MyAdapter(List<Class<? extends Fragment>> list){super(getSupportFragmentManager());mList = list;}@Overridepublic Fragment getItem(int position) {return Fragment.instantiate(MainActivity.this, mList.get(position).getName());}@Overridepublic int getCount() {return mList.size();}}}

5)写FragmentTabHost的布局文件

activity_tabhost.xml

<?xml version="1.0" encoding="utf-8"?><android.support.v4.app.FragmentTabHost    xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@android:id/tabhost"    android:layout_width="match_parent"    android:layout_height="match_parent">    <LinearLayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:orientation="vertical">        <FrameLayout            android:id="@android:id/tabcontent"            android:layout_width="match_parent"            android:layout_height="0dp"            android:layout_weight="0"/>        <FrameLayout            android:id="@+id/realtabcontent"            android:layout_width="match_parent"            android:layout_height="0dp"            android:layout_weight="1"/>                <TabWidget            android:id="@android:id/tabs"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:orientation="horizontal"/>    </LinearLayout></android.support.v4.app.FragmentTabHost>

6)写FragmentTabHost对应的FragmentActivity

public class TabHostActivity extends FragmentActivity {@Overrideprotected void onCreate(Bundle arg0) {super.onCreate(arg0);setContentView(R.layout.activity_tabhost);FragmentTabHost tabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);tabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);tabHost.addTab(tabHost.newTabSpec("A").setIndicator("First"), FirstFragment.class, null);tabHost.addTab(tabHost.newTabSpec("B").setIndicator("Second"), SecondFragment.class, null);tabHost.addTab(tabHost.newTabSpec("C").setIndicator("Third"), ThirdFragment.class, null);}}

2、示例2,SurfaceView及ViewPager的用法

一个Fragment可被多次使用;用到反射来动态加载图片

1)MainActivity.java

public class MainActivity extends FragmentActivity {private static final String TAG = MainActivity.class.getSimpleName();private ViewPager mViewPager;private static final int IMG_NUM = 3;@Overrideprotected void onCreate(Bundle arg0) {Log.d(TAG, "onCreate");getWindow().setFormat(PixelFormat.TRANSLUCENT);super.onCreate(arg0);setContentView(R.layout.activity_main);mViewPager = (ViewPager) findViewById(R.id.viewpager);List<Class<? extends Fragment>> list = new LinkedList<Class<? extends Fragment>>();list.add(DrawFragment.class);for(int i=0;i<IMG_NUM-1;i++){list.add(ImageFragment.class);}mViewPager.setAdapter(new MyAdapter(list));mViewPager.setOnPageChangeListener(new OnPageChangeListener() {@Overridepublic void onPageSelected(int position) {Log.d(TAG, "onPageSelected-"+position+"-"+mViewPager.findViewWithTag("draw"));}@Overridepublic void onPageScrolled(int position, float positionOffset,int positionOffsetPixels) {}@Overridepublic void onPageScrollStateChanged(int state) {}});}private class MyAdapter extends FragmentPagerAdapter{List<Class<? extends Fragment>> list;public MyAdapter(List<Class<? extends Fragment>> list) {super(getSupportFragmentManager());this.list = list;}@Overridepublic Fragment getItem(int position) {Log.d(TAG, "getItem-"+position);Fragment f = Fragment.instantiate(MainActivity.this, list.get(position).getName());switch (position) {case 0:break;case 1:case 2:((ImageFragment) f).setPosition(position);}return f;}@Overridepublic int getCount() {return list.size();}}}
2)activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    xmlns:android="http://schemas.android.com/apk/res/android">    <android.support.v4.view.ViewPager        android:id="@+id/viewpager"        android:layout_width="match_parent"        android:layout_height="match_parent"/></LinearLayout>
3)DrawFragment.java
public class DrawFragment extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {View v = inflater.inflate(R.layout.fragment_draw, container, false);return v;}}
4)fragment_draw.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    xmlns:android="http://schemas.android.com/apk/res/android">    <Button         android:id="@+id/btn_draw"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="photography"/>    <com.ivt.imagesdemo.MySurfaceView         android:id="@+id/mySurfaceView"        android:layout_width="match_parent"        android:layout_height="match_parent"/></LinearLayout>
5)MySurfaceView.java
public class MySurfaceView extends SurfaceView {private static final String TAG = MySurfaceView.class.getSimpleName();private SurfaceHolder mHolder;private Paint mPaint;public MySurfaceView(Context context){this(context,null);}public MySurfaceView(Context context, AttributeSet attrs){this(context, attrs, 0);}public MySurfaceView(Context context, AttributeSet attrs, int defStyleAttr){super(context, attrs, defStyleAttr);mHolder = getHolder();setBackgroundColor(Color.TRANSPARENT);setZOrderOnTop(true);mHolder.setFormat(PixelFormat.TRANSPARENT);mHolder.addCallback(new MyCallback());mPaint = new Paint();mPaint.setColor(Color.argb(255, 255, 0, 0));mPaint.setTextSize(context.getResources().getDisplayMetrics().density*20);setTag("draw");}private class MyCallback implements SurfaceHolder.Callback{@Overridepublic void surfaceCreated(SurfaceHolder holder) {Log.d(TAG, "surfaceCreated");Thread thread = new RenderThread();thread.start();}@Overridepublic void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {Log.d(TAG, "surfaceChanged");}@Overridepublic void surfaceDestroyed(SurfaceHolder holder) {Log.d(TAG, "surfaceDestroyed");}}private class RenderThread extends Thread{@Overridepublic void run() {super.run();Canvas canvas = mHolder.lockCanvas();canvas.drawColor(Color.argb(255, 255, 255, 255));//canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);canvas.drawText("从开始到现在——张信哲", 100, 100, mPaint);mHolder.unlockCanvasAndPost(canvas);}}@Overrideprotected void onVisibilityChanged(View changedView, int visibility) {Log.d(TAG, "onVisibilityChanged-"+visibility);super.onVisibilityChanged(changedView, visibility);if(visibility == VISIBLE){invalidate();}}}
6)ImageFragment.java
public class ImageFragment extends Fragment {private static final String TAG = ImageFragment.class.getSimpleName();private int position;@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {View view = inflater.inflate(R.layout.fragment_image, container, false);view.findViewById(R.id.btn).setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {Toast.makeText(getActivity(), "不是你哈", Toast.LENGTH_SHORT).show();}});ImageView imageView = (ImageView) view.findViewById(R.id.image);try {imageView.setImageResource(R.drawable.class.getField("pic_"+position).getInt(R.drawable.class.newInstance()));} catch (Exception e) {e.printStackTrace();}return view;}public void setPosition(int position) {this.position = position;}}
7)fragment_image.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    xmlns:android="http://schemas.android.com/apk/res/android">    <Button         android:id="@+id/btn"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="傻逼"/>    <ImageView         android:id="@+id/image"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:scaleType="fitXY"/></LinearLayout>
3、示例3

/** * <li>演示{@link ViewPager}的用法但未使用{@link FragmentActivity} * <li>ViewPager页为一系列View,通过inflate a view hierarchy from a xml resource得到 * <li>实现循环滑动 * <li>演示{@link PagerAdapter}和{@link OnPageChangeListener}的用法 */public class MainActivity extends Activity {private static final String TAG = MainActivity.class.getSimpleName();ViewPager pager;List<View> list;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);pager = (ViewPager) findViewById(R.id.viewPager);//LinearLayoutViewGroup view = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.view, null);List<View> list = new ArrayList<View>();list.add(view.findViewById(R.id.txt1));list.add(view.findViewById(R.id.txt2));list.add(view.findViewById(R.id.txt3));//IllegalStateException: The specified child already has a parent.view.removeAllViews();pager.setAdapter(new MyPagerAdapter(list));pager.setCurrentItem(0);pager.setOffscreenPageLimit(1);//defaultpager.setOnPageChangeListener(new MyOnPageChangeListener());}class MyPagerAdapter extends PagerAdapter{private List<View> list;public MyPagerAdapter(List<View> list){this.list = list;}@Overridepublic int getCount() {return Integer.MAX_VALUE;}@Overridepublic Object instantiateItem(ViewGroup container, int position) {Log.d(TAG, "instantiateItem-"+position);container.addView(list.get(position%list.size()));return list.get(position%list.size());}@Overridepublic void destroyItem(ViewGroup container, int position, Object object) {Log.d(TAG, "destroyItem-"+position);container.removeView(list.get(position%list.size()));}@Overridepublic boolean isViewFromObject(View arg0, Object arg1) {Log.d(TAG, "isViewFromObject");return arg0 == arg1;}}class MyOnPageChangeListener implements OnPageChangeListener{@Overridepublic void onPageScrollStateChanged(int state) {switch (state) {case ViewPager.SCROLL_STATE_IDLE:Log.d(TAG, "onPageScrollStateChanged-"+"SCROLL_STATE_IDLE");break;case ViewPager.SCROLL_STATE_DRAGGING:Log.d(TAG, "onPageScrollStateChanged-"+"SCROLL_STATE_DRAGGING");break;case ViewPager.SCROLL_STATE_SETTLING:Log.d(TAG, "onPageScrollStateChanged-"+"SCROLL_STATE_SETTLING");}}@Overridepublic void onPageScrolled(int position, float arg1, int arg2) {Log.d(TAG, "onPageScrolled-"+position);}@Overridepublic void onPageSelected(int position) {Log.d(TAG, "onPageSelected-"+position);}}}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical"    xmlns:android="http://schemas.android.com/apk/res/android">    <android.support.v4.view.ViewPager        android:id="@+id/viewPager"        android:layout_width="fill_parent"        android:layout_height="fill_parent"/></LinearLayout>
view.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical"    xmlns:android="http://schemas.android.com/apk/res/android">    <TextView         android:id="@+id/txt1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="haha"/>    <TextView         android:id="@+id/txt2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="hehe"/>    <TextView         android:id="@+id/txt3"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="heihei"/></LinearLayout>

0 0