使用ViewPager和Fragment實現滑動導航
ViewPage是android-support-v4.jar包提供的用于頁面滑動的庫,android-support-v4.jar是google推薦使用的一個類庫,在項目中使用之前,你必須其添加到項目中(項目點右鍵Build path->configure build path,然后找到jar進行添加)
1.在xml布局文件中添加android.support.v4.view.ViewPager容器及顯示導航所用標簽android.support.v4.view.PagerTitleStrip,如我添加的xml內容如下
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<!--
This title strip will display the currently visible page title, as well as the page
titles for adjacent pages.
-->
<android.support.v4.view.PagerTitleStrip
android:id="@+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#fff" />
</android.support.v4.view.ViewPager>
import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager;
3.聲明變量
SectionsPagerAdapter mSectionsPagerAdapter; ViewPager mViewPager;
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);5.添加類SectionsPagerAdapter,我這里使用了3個標簽 public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new HjFragment();
Bundle args = new Bundle();
args.putInt("no", position + 1);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "標簽1";
case 1:
return "標簽2";
case 2:
return "標簽3";
}
return null;
}
} 可以看到在getItem中返回了一個Fragment,這個就是當滑動到不同標簽時顯示在ViewPager中的內容,Fragment相當于一個Activity,在可以其中的onCreateView函數中構造需要顯示的內容并返回
比如,以下代碼將顯示一個文本信息
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER);
textView.setText("你選擇了標簽:"+Integer.toString(getArguments().getInt(
"no")));
return textView;
} 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!