Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

ViewPager + Fragment + ListView 組合實戰

編輯:關於 Android 程式設計

本文記錄一個常見組合:ViewPager + Fragment + ListView,配合 PagerSlidingTabStrip 實現頂部可滑動的 Tab 分類切換,每個 Tab 對應一個獨立的列表頁。這是資訊類 App 最典型的首頁結構。

一、Activity:裝配 Tab 與 Fragment

核心思路是準備兩個等長的集合——Fragment 列表與標題列表,交給 FragmentPagerAdapter 的子類去裝配。這裡通過 Bundle 給每個 Fragment 傳一個 arg 參數,用來決定它內部該展示哪一類數據。

public class VpFragmentLvActivity extends AppCompatActivity {

    private ViewPager vp;
    private PagerSlidingTabStrip pst;

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

        vp = (ViewPager) findViewById(R.id.vp);
        pst = (PagerSlidingTabStrip) findViewById(R.id.pst);

        List<Fragment> list = new ArrayList<>();
        List<String> titles = new ArrayList<>();
        titles.add("推薦");
        titles.add("熱點");
        titles.add("煙台");
        titles.add("視頻");
        titles.add("訂閱");
        titles.add("體育");
        titles.add("娛樂");
        titles.add("奧運");
        titles.add("財經");
        titles.add("國際");

        // 每個 Tab 對應一個 Fragment 實例,並通過 Bundle 傳遞標識
        for (int i = 1; i <= titles.size(); i++) {
            Fragment fragment = new VpFragmentLv();
            Bundle bundle = new Bundle();
            bundle.putInt("arg", i);
            fragment.setArguments(bundle);
            list.add(fragment);
        }

        MyVpFragmentAdapter ma =
                new MyVpFragmentAdapter(getSupportFragmentManager(), list, titles);
        vp.setAdapter(ma);

        // Tab 指示器樣式
        pst.setIndicatorColor(getResources().getColor(R.color.colorPrimary));
        pst.setIndicatorHeight(5);
        pst.setAllCaps(true);
        pst.setShouldExpand(true);   // 標題平分寬度
        pst.setTextColor(getResources().getColor(R.color.colorAccent));
        pst.setViewPager(vp);
    }
}

Activity 布局:頂部紅色標題欄 + PagerSlidingTabStrip + 日期信息欄。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:id="@+id/rr"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#ef4848">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="今日頭條"
            android:textColor="#ffffff"
            android:textSize="26sp" />

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:src="@mipmap/base_main_action_personal_normal" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:src="@mipmap/right_drawer_normal" />
    </RelativeLayout>

    <com.astuetz.pagerslidingtabstrip.PagerSlidingTabStrip
        android:id="@+id/pst"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_below="@+id/rr" />

    <LinearLayout
        android:id="@+id/ll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/pst"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="30dp"
            android:layout_marginLeft="20dp"
            android:text="2016.08.09" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="30dp"
            android:layout_marginLeft="50dp"
            android:text="星期二" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="30dp"
            android:layout_marginLeft="120dp"
            android:text="今天" />
    </LinearLayout>
</RelativeLayout>

二、Fragment:內部裝一個 ListView

Fragment 在 onActivityCreated 中初始化列表,從 getArguments() 取出 Activity 傳來的 arg,據此灌入不同的假數據。

public class VpFragmentLv extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_vp_fragment_lv, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        ListView lv = (ListView) getView().findViewById(R.id.lv);
        final List<News> list = new ArrayList<>();
        MyListAdapter ma = new MyListAdapter(list, getActivity());
        lv.setAdapter(ma);

        // Item 點擊:跳轉並同時傳遞 Parcelable 對象與 Bundle
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                News news = list.get(i);
                Intent intent = new Intent(getActivity(), IntentActivity.class);
                intent.putExtra("obj", news);
                Bundle b1 = new Bundle();
                b1.putString("arg1", "今天七月七");
                intent.putExtra("bundle", b1);
                startActivity(intent);
            }
        });

        Bundle bundle = getArguments();
        if (bundle != null) {
            int arg = bundle.getInt("arg");
            switch (arg) {
                case 1:
                    for (int i = 0; i < 20; i++) {
                        list.add(new News("體育新聞" + i, "今天", "0001",
                                R.mipmap.zyfzyf, "新浪網"));
                    }
                    break;
                case 2:
                    for (int i = 0; i < 20; i++) {
                        list.add(new News("煙台新聞" + i, "今天", "0002",
                                R.mipmap.zyf, "新浪網"));
                    }
                    break;
                case 3:
                    for (int i = 0; i < 20; i++) {
                        list.add(new News("奧運新聞" + i, "今天", "0003",
                                R.mipmap.zz, "新浪網"));
                    }
                    break;
            }
            ma.notifyDataSetChanged();
        }
    }
}

Fragment 布局:

<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</FrameLayout>

三、數據模型:實現 Parcelable

Inter-Activity 傳遞對象時,Parcelable 比 Serializable 效率更高,是 Android 的推薦做法。

public class News implements Parcelable {

    private String title;
    private String pubDate;
    private int img;
    private String from;

    public News(String title, String pubDate, String newId, int img, String from) {
        this.title = title;
        this.pubDate = pubDate;
        this.img = img;
        this.from = from;
    }

    protected News(Parcel in) {
        title = in.readString();
        pubDate = in.readString();
        img = in.readInt();
        from = in.readString();
    }

    public static final Creator<News> CREATOR = new Creator<News>() {
        @Override
        public News createFromParcel(Parcel in) {
            return new News(in);
        }

        @Override
        public News[] newArray(int size) {
            return new News[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(title);
        parcel.writeString(pubDate);
        parcel.writeInt(img);
        parcel.writeString(from);
    }

    // getter / setter 省略
}

四、Pager 適配器

public class MyVpFragmentAdapter extends FragmentPagerAdapter {

    private List<Fragment> list;
    private List<String> titles;

    public MyVpFragmentAdapter(FragmentManager fm, List<Fragment> list,
                               List<String> titles) {
        super(fm);
        this.list = list;
        this.titles = titles;
    }

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

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

    @Override
    public CharSequence getPageTitle(int position) {
        return titles.get(position);
    }
}

運行效果:

五、另一種 Tab 方案:FragmentTabHost

除了 ViewPager,也可以用 FragmentTabHost 做底部 Tab 切換。核心是用 newTabSpec 配合自定義的指示器 View:

public class FragmentTabHostActivity extends AppCompatActivity {

    private ViewPager vp;
    private FragmentTabHost ft;

    private String[] str = {"首頁", "消息", "更多", "好友", "搜索"};
    private int[] imgRes = {R.drawable.home, R.drawable.meassage, R.drawable.more,
                            R.drawable.selfinfo, R.drawable.square};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment_tab_host);
        vp = (ViewPager) findViewById(R.id.vp);
        ft = (FragmentTabHost) findViewById(R.id.ft);
        init();
    }

    /** 構造帶圖標與文字的 Tab 指示器 */
    private View getView(int position) {
        View v = getLayoutInflater().inflate(R.layout.tab_layout, null);
        ImageView iv = (ImageView) v.findViewById(R.id.iv);
        TextView tv = (TextView) v.findViewById(R.id.tv);
        iv.setImageResource(imgRes[position]);
        tv.setText(str[position]);
        return v;
    }

    private void init() {
        List<Fragment> list = new ArrayList<>();
        ft.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
        for (int i = 0; i < str.length; i++) {
            TabHost.TabSpec spec = ft.newTabSpec(str[i]).setIndicator(getView(i));
            ft.addTab(spec, TabHostFragment.class, null);
        }
    }
}

Tab 指示器的 selector:

<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:drawable="@mipmap/icon_home_sel" android:state_selected="true" />
    <item android:drawable="@mipmap/icon_home_nor" />
</selector>

TabHostFragment 的實現與前面類似,通過 getArguments() 拿參數更新界面:

public class TabHostFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_tab_host, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        TextView tv = (TextView) getView().findViewById(R.id.tv);
        Bundle bundle = getArguments();
        if (bundle != null) {
            int arg = bundle.getInt("arg");
            tv.setText("我是Fragment" + (arg + 1));
        }
    }
}

關鍵點回顧

這個組合裡最容易踩的坑有三個:一是 Fragment 依賴宿主 Context,务必在 onActivityCreated 而非構造函數裡初始化視圖;二是 FragmentPagerAdapter 的 getCount 與 Fragment 列表長度必須一致,否則會出現空白頁;三是往 Intent 傳對象時,Parcelable 的 writeToParcel 讀寫順序必須嚴格對應,順序錯了就會拿到髒數據。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved