Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android中ViewPager和Fragment的使用

Android中ViewPager和Fragment的使用

編輯:關於Android編程

小案例

XML中

<android.support.v4.view.ViewPager
  android:id="@+id/viewPager"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
</android.support.v4.view.ViewPager>

創建Fragment

 fragments = new ArrayList<>();
 ConversationFragment fragment1 = new ConversationFragment();
 GroupFragment fragment2 = new GroupFragment();
 SearchFragment fragment3 = new SearchFragment();
 fragments.add(fragment1);
 fragments.add(fragment2);
 fragments.add(fragment3);
 adapter = new MainPagerAdapter(getSupportFragmentManager(), fragments);
 viewPager.setAdapter(adapter);

adapter

public class MainPagerAdapter extends FragmentPagerAdapter{

  List<Fragment> fragmentList;

  public MainPagerAdapter(FragmentManager fm, List<Fragment> fragmentList) {
    super(fm);
    this.fragmentList = fragmentList;
  }

  @Override
  public Fragment getItem(int position) {
    return fragmentList.get(position);
  }

  @Override
  public int getCount() {
    return fragmentList.size();
  }
}

OnPageChangeListener

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
  @Override
  public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    int distance = positionOffsetPixels / 3;
    //一旦fragment滑動,這裡的position實際是前一個的
    ViewPropertyAnimator.animate(v_indicate_line).translationX(distance + position * v_indicate_line.getWidth()).setDuration(0);
  }

  @Override
  public void onPageSelected(int position) {
    textLightAndSize();
  }


  @Override
  public void onPageScrollStateChanged(int state) {

  }
});

配合其他點擊事件

//這裡是注意setCurrentItem的用法
switch (view.getId()) {
  case R.id.ly_conversation:
    viewPager.setCurrentItem(0);
    break;
  case R.id.ly_group:
    viewPager.setCurrentItem(1);
    break;
  case R.id.ly_search:
    viewPager.setCurrentItem(2);
    break;
}

官方案例

R.layout.fragment_pager

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:padding="4dip"
    android:gravity="center_horizontal"
    android:layout_width="match_parent" android:layout_height="match_parent">

  <android.support.v4.view.ViewPager
      android:id="@+id/pager"
      android:layout_width="match_parent"
      android:layout_height="0px"
      android:layout_weight="1">
  </android.support.v4.view.ViewPager>

  <LinearLayout android:orientation="horizontal"
      android:gravity="center" android:measureWithLargestChild="true"
      android:layout_width="match_parent" android:layout_height="wrap_content"
      android:layout_weight="0">
    <Button android:id="@+id/goto_first"
      android:layout_width="wrap_content" android:layout_height="wrap_content"
      android:text="@string/first">
    </Button>
    <Button android:id="@+id/goto_last"
      android:layout_width="wrap_content" android:layout_height="wrap_content"
      android:text="@string/last">
    </Button>
  </LinearLayout>
</LinearLayout>

R.layout.fragment_pager_list

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@android:drawable/gallery_thumb">

  <TextView android:id="@+id/text"
    android:layout_width="match_parent" android:layout_height="wrap_content"
    android:gravity="center_vertical|center_horizontal"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="@string/hello_world"/>

  <!-- The frame layout is here since we will be showing either
  the empty view or the list view. -->
  <FrameLayout
    android:layout_width="match_parent"
    android:layout_height="0dip"
    android:layout_weight="1" >
    <!-- Here is the list. Since we are using a ListActivity, we
       have to call it "@android:id/list" so ListActivity will
       find it -->
    <ListView android:id="@android:id/list"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:drawSelectorOnTop="false"/>

    <!-- Here is the view to show if the list is emtpy -->
    <TextView android:id="@android:id/empty"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:textAppearance="?android:attr/textAppearanceMedium"
      android:text="No items."/>

  </FrameLayout>

</LinearLayout>

public class FragmentPagerSupport extends FragmentActivity {
  static final int NUM_ITEMS = 10;

  MyAdapter mAdapter;

  ViewPager mPager;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_pager);

    mAdapter = new MyAdapter(getSupportFragmentManager());

    mPager = (ViewPager)findViewById(R.id.pager);
    mPager.setAdapter(mAdapter);

    // Watch for button clicks.
    Button button = (Button)findViewById(R.id.goto_first);
    button.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        mPager.setCurrentItem(0);
      }
    });
    button = (Button)findViewById(R.id.goto_last);
    button.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        mPager.setCurrentItem(NUM_ITEMS-1);
      }
    });
  }

  public static class MyAdapter extends FragmentPagerAdapter {
    public MyAdapter(FragmentManager fm) {
      super(fm);
    }

    @Override
    public int getCount() {
      return NUM_ITEMS;
    }

    @Override
    public Fragment getItem(int position) {
      return ArrayListFragment.newInstance(position);
    }
  }

  public static class ArrayListFragment extends ListFragment {
    int mNum;

    /**
     * Create a new instance of CountingFragment, providing "num"
     * as an argument.
     */
    static ArrayListFragment newInstance(int num) {
      ArrayListFragment f = new ArrayListFragment();

      // Supply num input as an argument.
      Bundle args = new Bundle();
      args.putInt("num", num);
      f.setArguments(args);

      return f;
    }

    /**
     * When creating, retrieve this instance's number from its arguments.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      mNum = getArguments() != null ? getArguments().getInt("num") : 1;
    }

    /**
     * The Fragment's UI is just a simple text view showing its
     * instance number.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
      View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
      View tv = v.findViewById(R.id.text);
      ((TextView)tv).setText("Fragment #" + mNum);
      return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
      super.onActivityCreated(savedInstanceState);
      setListAdapter(new ArrayAdapter<String>(getActivity(),
          android.R.layout.simple_list_item_1, Cheeses.sCheeseStrings));
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
      Log.i("FragmentList", "Item clicked: " + id);
    }
  }
}

注意

3.0之前的Activity是不能用fragment的。為了能使用fragment(supportV4中),才有了FragmentActivity。FragmentActivity繼承的Activity。

以上就是本文的全部內容,希望對大家學習Android軟件編程有所幫助。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved