編輯:關於 Android 程式設計

本文記錄一個常見組合:ViewPager + Fragment + ListView,配合 PagerSlidingTabStrip 實現頂部可滑動的 Tab 分類切換,每個 Tab 對應一個獨立的列表頁。這是資訊類 App 最典型的首頁結構。
核心思路是準備兩個等長的集合——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 在 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>
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 省略
}
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);
}
}
運行效果:


除了 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 讀寫順序必須嚴格對應,順序錯了就會拿到髒數據。
Android 自定義 View:用觀察者模式實作字母索引欄
字母索引欄常見於通訊錄、音樂與相簿。這個自定義 View 會依觸控位置判斷目前選到的字母,並透過監聽器回傳給 Activity。 實作時,先定義 OnItemListe
一篇搞懂設計模式:單例模式(Singleton)完全解析
前言 在 Android 乃至整個物件導向開發領域,單例模式無疑是最常被提及、也最容易被寫錯的一種設計模式。本文將從「它究竟解決了什麼問題」出發,配合一個倉庫管理的實作案
Android View 系統解析(上):從 View 樹到測量、佈局、繪製三大流程
寫 Android 介面久了,難免會遇到一些「表面寫得出來、深究卻說不清」的問題:為什麼自訂 View 的 onMeasure 不寫就顯示不出來?requestLayou
Android Studio 找不到 recyclerview-v7?先搞懂 support 庫的拆分方式
在 Android Studio 裡寫 RecyclerView 時,如果直接照著網路上的教學加入依賴,很可能會看到「找不到 com.android.support:re