你的位置:首页 > 操作系统

[操作系统]ViewPager+fragment的简单使用


借鉴http://blog.csdn.net/wangjinyu501/article/details/8169924而来

fragment是为了简化actvity与view之间的交互而将activity对用户交互的逻辑模块化进行的封装,它的好处是:1>简化activity的逻辑控制 2>这些模块化的fragment也更利于复用。

    Fragment有如下特点:
1>Fragment表现为一个activity用户界面的一部分
2>一个activity可以有多个fragment
3>可以在多个activity中复用fragment
4>fragment有自己的生命周期
5>fragment有自己的事件处理
6>activity运行中,可以添加,移除一个fragment
7>fragment的生命周期有其宿主activity控制
如图是效果图
    代码运行虽然没问题 但是我在viewpager中传入动态数据时,数据在viewpager中显示不对应或有的不显示
  看网上别人说是FragmentPagerAdapter中的instantiateItem方法要重写,能力不够 没搞懂
 

 
如下是布局文件
<??><RelativeLayout ="http://schemas.android.com/apk/res/android"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:background="#eee" >  <LinearLayout    android:id="@+id/ll_main_text"    android:layout_width="match_parent"    android:layout_height="50dp"    android:background="#FF7200"    android:gravity="center_vertical" >    <LinearLayout      android:layout_width="60dp"      android:layout_height="match_parent"      android:gravity="center" >      <ImageView        android:layout_width="30dp"        android:layout_height="30dp"        android:contentDescription="@null"        android:scaleType="fitCenter"        android:src="@drawable/arrow_left" />    </LinearLayout>    <View      android:layout_width="0.5dp"      android:layout_height="match_parent"      android:background="#FE8B40" />    <TextView      android:layout_width="0dp"      android:layout_height="match_parent"      android:layout_weight="0.8"      android:gravity="center"      android:text="限时购"      android:textColor="@android:color/white"      android:textSize="20sp" />    <View      android:layout_width="0.5dp"      android:layout_height="match_parent"      android:background="#FE8B40" />    <LinearLayout      android:layout_width="60dp"      android:layout_height="match_parent"      android:gravity="center" >      <ImageView        android:layout_width="30dp"        android:layout_height="30dp"        android:contentDescription="@null"        android:scaleType="fitCenter"        android:src="@drawable/dropdown" />    </LinearLayout>  </LinearLayout>  <!-- -->  <LinearLayout    android:id="@+id/ll_text_mainout"    android:layout_width="match_parent"    android:layout_height="55dp"    android:layout_alignParentBottom="true"    android:background="#eee"    android:gravity="center_vertical"    android:orientation="vertical" >    <View      android:layout_width="match_parent"      android:layout_height="0.5dp"      android:background="#999999" />    <LinearLayout      android:layout_width="match_parent"      android:layout_height="match_parent"      android:baselineAligned="false"      android:gravity="center"      android:orientation="horizontal" >      <RelativeLayout        android:layout_width="0dp"        android:layout_height="match_parent"        android:layout_weight="1" >        <Button          android:id="@+id/bb_text_main1"          android:layout_width="match_parent"          android:layout_height="match_parent"          android:drawableTop="@drawable/main_topcolor"          android:paddingBottom="2dp"          android:paddingTop="5dp"          android:text="限时抢购"          android:textColor="@color/main_bottoncolor" />      </RelativeLayout>      <RelativeLayout        android:layout_width="0dp"        android:layout_height="match_parent"        android:layout_weight="1" >        <Button          android:layout_width="match_parent"          android:layout_height="match_parent"          android:drawableTop="@drawable/main_topcolor"          android:paddingBottom="2dp"          android:paddingTop="5dp"          android:text="限时抢购"          android:textColor="@color/main_bottoncolor" />      </RelativeLayout>      <RelativeLayout        android:layout_width="0dp"        android:layout_height="match_parent"        android:layout_weight="1" >        <Button          android:layout_width="match_parent"          android:layout_height="match_parent"          android:drawableTop="@drawable/main_topcolor"          android:paddingBottom="2dp"          android:paddingTop="5dp"          android:text="限时抢购"          android:textColor="@color/main_bottoncolor" />      </RelativeLayout>    </LinearLayout>  </LinearLayout>  <!-- -->  <LinearLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    android:layout_above="@id/ll_text_mainout"    android:layout_below="@id/ll_main_text"    android:background="@android:color/white"    android:orientation="vertical" >    <LinearLayout      android:id="@+id/linearlayout1"      android:layout_width="match_parent"      android:layout_height="50.0dip"      android:layout_gravity="center"      android:background="#FFFFFF" >      <TextView        android:id="@+id/text1"        android:layout_width="0dp"        android:layout_height="match_parent"        android:layout_weight="1.0"        android:gravity="center"        android:text="页卡1"        android:textColor="#000000"        android:textSize="22.0dip" />      <TextView        android:id="@+id/text2"        android:layout_width="0dp"        android:layout_height="match_parent"        android:layout_weight="1.0"        android:gravity="center"        android:text="页卡2"        android:textColor="#000000"        android:textSize="22.0dip" />      <TextView        android:id="@+id/text3"        android:layout_width="0dp"        android:layout_height="match_parent"        android:layout_weight="1.0"        android:gravity="center"        android:text="页卡3"        android:textColor="#000000"        android:textSize="22.0dip" />    </LinearLayout>    <TextView      android:id="@+id/cursor"      android:layout_width="100dp"      android:layout_height="5dp"      android:background="#990033" />    <android.support.v4.view.ViewPager      android:id="@+id/vPager"      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:layout_gravity="center"      android:background="#000000"      android:flipInterval="30"      android:persistentDrawingCache="animation" />  </LinearLayout></RelativeLayout>

主代码
如下

package org.import java.util.ArrayList;import ogg.huanxin.huadong.R;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentActivity;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentPagerAdapter;import android.support.v4.view.ViewPager;import android.support.v4.view.ViewPager.OnPageChangeListener;import android.util.DisplayMetrics;import android.view.Display;import android.view.View;import android.view.Window;import android.widget.LinearLayout;import android.widget.LinearLayout.LayoutParams;import android.widget.TextView;public class MyViewpager extends FragmentActivity {  private ViewPager mPager;  private TextView barText;  private TextView view1, view2, view3;  private ArrayList<Fragment> fragmentlist;  private int currIndex;// 当前的叶卡标号  @Override  protected void onCreate(Bundle arg0) {    // TODO Auto-generated method stub    super.onCreate(arg0);    requestWindowFeature(Window.FEATURE_NO_TITLE);    // setContentView(R.layout.myciewpager);    setContentView(R.layout.mypager);    InitTextView();    InitTextBar();    InitViewPager();  }  /*   * 初始化标签名字   */  private void InitTextView() {    // TODO Auto-generated method stub    view1 = (TextView) findViewById(R.id.text1);    view2 = (TextView) findViewById(R.id.text2);    view3 = (TextView) findViewById(R.id.text3);    view1.setOnClickListener(new txListener(0));    view2.setOnClickListener(new txListener(1));    view3.setOnClickListener(new txListener(2));  }  public class txListener implements View.OnClickListener {    private int index = 0;    public txListener(int i) {      index = i;    }    @Override    public void onClick(View arg0) {      // TODO Auto-generated method stub      mPager.setCurrentItem(index);    }  }  /*   * 初始化图片的位移像素   */  private void InitTextBar() {    // TODO Auto-generated method stub    barText = (TextView) super.findViewById(R.id.cursor);    Display display = getWindow().getWindowManager().getDefaultDisplay();    // 得到显示的屏宽度    DisplayMetrics metrics = new DisplayMetrics();    display.getMetrics(metrics);    int tabLimeLength = metrics.widthPixels / 3;    LayoutParams lp = (LayoutParams) barText.getLayoutParams();    lp.width = tabLimeLength;    barText.setLayoutParams(lp);  }  /*   * 初始化ViewPager   */  private void InitViewPager() {    // TODO Auto-generated method stub    mPager = (ViewPager) findViewById(R.id.vPager);    fragmentlist = new ArrayList<Fragment>();    Fragment btFragment = new Fragment1();    Fragment fragment2 = new Fragment2();    Fragment fragment3 = new Fragment3();    fragmentlist.add(btFragment);    fragmentlist.add(fragment2);    fragmentlist.add(fragment3);    // 给ViewPager设置适配器    mPager.setAdapter(new MyFragmentPagerAdapter(        getSupportFragmentManager(), fragmentlist));    mPager.setCurrentItem(0); // 设置当前显示标签页为第一页    // mPager.setOnPageChangeListener(new MyPn);    mPager.setOnPageChangeListener(new MyOnpageChangeListener());// 页面变化时的监听器  }  private class MyOnpageChangeListener implements OnPageChangeListener {    @Override    public void onPageScrollStateChanged(int arg0) {      // onPageScrollStateChanged(int arg0)      // 表示当前滑动的状态,只有三个状态0(END),1(PRESS) , 2(UP),    }    @Override    public void onPageScrolled(int arg0, float arg1, int arg2) {      // onPageScrolled(int arg0, float arg1, int arg2)      // arg0表示目标,arg1表示偏移的百分比,arg2表示偏移的像素      LinearLayout.LayoutParams ll = (LayoutParams) barText          .getLayoutParams();      if (currIndex == arg0) {        ll.leftMargin = (int) (currIndex * barText.getWidth() + arg1            * barText.getWidth());      } else if (currIndex > arg0) {        ll.leftMargin = (int) (currIndex * barText.getWidth() - (1 - arg1)            * barText.getWidth());      }      barText.setLayoutParams(ll);    }    @Override    public void onPageSelected(int arg0) {      // onPageSelected(int arg0) 指的是当前选择的是哪个页面      currIndex = arg0;      // int i = currIndex + 1;      // Toast.makeText(MyViewpager.this, "您选择了第" + i + "个叶卡",      // Toast.LENGTH_SHORT).show();    }  }  private class MyFragmentPagerAdapter extends FragmentPagerAdapter {    private ArrayList<Fragment> list;    public MyFragmentPagerAdapter(FragmentManager fm,        ArrayList<Fragment> list) {      super(fm);      this.list = list;      // TODO Auto-generated constructor stub    }    @Override    public Fragment getItem(int arg0) {      // TODO Auto-generated method stub      return list.get(arg0);    }    @Override    public int getCount() {      // TODO Auto-generated method stub      return list.size();    }    @Override    public int getItemPosition(Object object) {      // TODO Auto-generated method stub      return super.getItemPosition(object);    }  }}

其中的fragment的一个主代码和布局如下

其中3个fragment你可以随便写的

package org.import org.import org.import ogg.huanxin.huadong.R;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.Toast;public class Fragment1 extends Fragment {  private MyGridView myGridView;  /** 产品的适配器 */  private ProducteGridAdapter producteGridAdapter;  @Override  public View onCreateView(LayoutInflater inflater, ViewGroup container,      Bundle savedInstanceState) {    return inflater.inflate(R.layout.fragment1, container, false);  }  @Override  public void onActivityCreated(Bundle savedInstanceState) {    super.onActivityCreated(savedInstanceState);    setFindViewById();    setListener();  }  private void setFindViewById() {    myGridView = (MyGridView) getActivity().findViewById(        R.id.my_fragment1_view);    producteGridAdapter = new ProducteGridAdapter(getActivity());    myGridView.setAdapter(producteGridAdapter);  }  private void setListener() {    myGridView.setOnItemClickListener(new OnItemClickListener() {      @Override      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,          long arg3) {        // TODO Auto-generated method stub        Toast.makeText(getActivity(), "你点击了" + arg2, Toast.LENGTH_SHORT)            .show();      }    });  }}

View Code
<?  android:layout_width="match_parent"  android:layout_height="match_parent"  android:orientation="vertical" >  <ImageView    android:layout_width="match_parent"    android:layout_height="100dp"    android:contentDescription="@null"    android:visibility="gone"    android:scaleType="fitCenter"    android:src="@drawable/a" />  <ScrollView    android:layout_width="match_parent"    android:layout_height="wrap_content" >    <LinearLayout      android:layout_width="match_parent"      android:layout_height="wrap_content"      android:orientation="vertical" >      <org.="@+id/my_fragment1_view"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:horizontalSpacing="4dp"        android:numColumns="2"        android:verticalSpacing="7dp" >      </org.
View Code