編輯:關於 Android 開發
這篇把一個完整的側滑選單範例拆開來講,涵蓋的知識點不少:Fragment 的動態切換、Fragment 與 Activity 之間的回調溝通、網路 JSON 資料的異步抓取與解析、ListView 的多種 Item 版面與快取優化。
MainActivity 繼承 SlidingActivity,同時實作四個 Fragment 各自的回呼介面。這種寫法的好處是編譯期就能檢查契約——如果 Activity 忘了實作某個介面,編譯就會直接報錯。
public class MainActivity extends SlidingActivity
implements Cehua_Fragment.SetonCehuaFragmentClickListener,
Fragment_one.SetonFragmentOneClickListener,
Fragment_tiyuxinwen.SetonFragmentTiyuxinwenClickListener,
Fragment_yulexinwen.SetonFragmentYulexinwenClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction()
.add(R.id.main_framelayout, Fragment_one.newFragment()).commit();
// 設定滑出菜單的版面
setBehindContentView(R.layout.demo);
getFragmentManager().beginTransaction()
.add(R.id.demo, Cehua_Fragment.newFragment()).commit();
SlidingMenu slidingMenu = getSlidingMenu();
slidingMenu.setBehindOffsetRes(R.dimen.weight); // 側滑露出的寬度
}
@Override
public void loadxinwen() {
getFragmentManager().beginTransaction()
.replace(R.id.main_framelayout, Fragment_one.newFragment()).commit();
toggle(); // 切完畫面順手收起側邊選單
}
@Override
public void loadyulexinwen() {
getFragmentManager().beginTransaction()
.replace(R.id.main_framelayout, Fragment_yulexinwen.newFragment()).commit();
toggle();
}
@Override
public void loadtiyuxinwen() {
getFragmentManager().beginTransaction()
.replace(R.id.main_framelayout, Fragment_tiyuxinwen.newFragment()).commit();
toggle();
}
@Override
public void back() {
toggle();
}
}
關鍵在 onAttach()。Fragment 被掛上 Activity 的那一刻,就把宿主轉型成自己定義的介面;轉型失敗就丟例外,逼自己在開發階段發現問題。之後 Fragment 內部任何時候要通知 Activity,直接呼叫介面方法即可。
public class Cehua_Fragment extends Fragment {
private SetonCehuaFragmentClickListener mListener;
public interface SetonCehuaFragmentClickListener {
void loadxinwen();
void loadyulexinwen();
void loadtiyuxinwen();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof SetonCehuaFragmentClickListener) {
mListener = (SetonCehuaFragmentClickListener) activity;
} else {
throw new RuntimeException(activity.toString() + " 必須實作回呼介面");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.cehua_menu, null);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
getView().findViewById(R.id.monixinweijiem).setOnClickListener(v -> mListener.loadxinwen());
getView().findViewById(R.id.yulexinwen).setOnClickListener(v -> mListener.loadyulexinwen());
getView().findViewById(R.id.tiyuxinwen).setOnClickListener(v -> mListener.loadtiyuxinwen());
super.onActivityCreated(savedInstanceState);
}
public static Cehua_Fragment newFragment() {
return new Cehua_Fragment();
}
}
其他兩個 Fragment(娛樂新聞、體育新聞)結構完全相同,只有一個 back() 方法,這裡不再重複貼。
AsyncHttpClient 負責非同步請求,Gson 負責把回應字串直接映射成物件。你只要把 JSON 的結構對應成 POJO,剩下的交給 Gson:
private void GetAsynchttpdata() {
AsyncHttpClient ahc = new AsyncHttpClient();
ahc.get(net_url, new TextHttpResponseHandler() {
@Override
public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
Toast.makeText(getActivity(), "錯誤!", 0).show();
}
@Override
public void onSuccess(int arg0, Header[] arg1, String arg2) {
Gson gson = new Gson();
Infoall infoall = gson.fromJson(arg2, Infoall.class);
Info info = infoall.getInfo();
List<MerchantKey> mMerchantKey = info.getMerchantKey();
mMyAdapter.setList(mMerchantKey);
lv.stopRefresh();
lv.stopLoadMore();
}
});
}
對應的資料類別非常單純,就是有欄位、有 getter/setter:
public class Infoall {
private Info info;
public Info getInfo() { return info; }
public void setInfo(Info info) { this.info = info; }
}
public class Info {
private List<MerchantKey> merchantKey;
public List<MerchantKey> getMerchantKey() { return merchantKey; }
public void setMerchantKey(List<MerchantKey> merchantKey) {
this.merchantKey = merchantKey;
}
}
public class MerchantKey {
private String name;
private String coupon;
private String location;
private String distance;
private String picUrl;
private String couponType;
private String cardType;
private String groupType;
// 各欄位的 getter / setter 省略
}
這裡有個實務上的重要提醒:POJO 的欄位名稱必須和 JSON 的 key 完全一致,否則 Gson 會靜默地給你 null,不會報錯,這種 bug 特別難查。若欄位名不能用(例如是 Java 關鍵字),可以改用 @SerializedName 註解對應。
Adapter 依資料中的 couponType 決定要用哪種版面,這裡有兩個必寫的方法:
@Override
public int getItemViewType(int position) {
// equalsIgnoreCase 對大小寫不敏感
if (data.get(position).getCouponType().equalsIgnoreCase("YES")) {
return TYPE_ONE;
} else {
return TYPE_TWO;
}
}
@Override
public int getViewTypeCount() {
return 2; // 不寫這個方法容易出錯
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (getItemViewType(position) == TYPE_ONE) {
return getViewOne(position, convertView, parent);
} else {
return getViewTwo(position, convertView, parent);
}
}
單一版面的 getView 則是標準的 ViewHolder 兩段式優化:
public View getViewOne(int position, View convertView, ViewGroup parent) {
Viewdata mviewdata;
if (convertView == null) {
// 一級優化:convertView 復用,避免大量配置物件
mviewdata = new Viewdata();
convertView = flater.inflate(R.layout.list, null);
mviewdata.biaoti = (TextView) convertView.findViewById(R.id.list_name_txt);
mviewdata.biaoti2 = (TextView) convertView.findViewById(R.id.list_coupe_txt);
mviewdata.dizhi = (TextView) convertView.findViewById(R.id.list_location_txt);
mviewdata.juli = (TextView) convertView.findViewById(R.id.list_distance_txt);
mviewdata.jpg = (ImageView) convertView.findViewById(R.id.list_icon_img);
mviewdata.tuan = (ImageView) convertView.findViewById(R.id.list_group_img);
mviewdata.quan = (ImageView) convertView.findViewById(R.id.list_ticket_img);
mviewdata.ka = (ImageView) convertView.findViewById(R.id.list_card_img);
convertView.setTag(mviewdata);
}
// 二級優化:findViewById 只做一次,直接從 tag 取回
mviewdata = (Viewdata) convertView.getTag();
mviewdata.biaoti.setText(data.get(position).getName());
mviewdata.biaoti2.setText(data.get(position).getCoupon());
mviewdata.dizhi.setText(data.get(position).getLocation());
mviewdata.juli.setText(data.get(position).getDistance());
Picasso.with(context).load(data.get(position).getPicUrl()).into(mviewdata.jpg);
// 依資料決定小圖示的顯示
mviewdata.tuan.setVisibility(data.get(position).getGroupType().equals("YES")
? View.VISIBLE : View.GONE);
mviewdata.ka.setVisibility(data.get(position).getCardType().equals("YES")
? View.VISIBLE : View.GONE);
mviewdata.quan.setVisibility(data.get(position).getCouponType().equals("YES")
? View.VISIBLE : View.GONE);
return convertView;
}
這裡有個新手常犯的錯誤值得點出來:Item 內的小圖示一律要明確設定 VISIBLE 或 GONE,不能只在需要顯示時設 VISIBLE。因為 convertView 會被回收重複使用,一個「有團購標籤」的 Item 被回收去顯示「沒有團購」的資料時,如果沒显式設 GONE,標籤就會殘留上去,畫面看起來像是資料錯位。
主容器用 FrameLayout 當 Fragment 的掛載點:
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/main_framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
側滑選單的內容是一個直線排列的區塊:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="選擇您要的項目"
android:textColor="#03A9F4"
android:textSize="25sp" />
<Button android:id="@+id/monixinweijiem" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="模擬新聞界面" />
<Button android:id="@+id/yulexinwen" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="娛樂新聞" />
<Button android:id="@+id/tiyuxinwen" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="體育新聞" />
</LinearLayout>
新聞列表頁則是 XListView 加上一個載入中的 ProgressBar:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="@layout/title_layout" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<me.maxwin.view.XListView
android:id="@+id/xlv"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="@+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>
</LinearLayout>
Item 版面用 RelativeLayout 排「左圖右文」,右下角落距離、上方放標籤圖示:
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="@android:color/white">
<ImageView
android:id="@+id/list_icon_img"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/list_name_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/list_icon_img"
android:singleLine="true"
android:textColor="@android:color/background_dark"
android:textSize="16sp" />
<TextView
android:id="@+id/list_coupe_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/list_name_txt"
android:layout_toRightOf="@id/list_icon_img"
android:textColor="@android:color/holo_red_dark"
android:textSize="14sp" />
<TextView
android:id="@+id/list_distance_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:drawableLeft="@drawable/info_map"
android:textSize="14sp" />
<TextView
android:id="@+id/list_location_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="@id/list_distance_txt"
android:layout_toRightOf="@id/list_icon_img"
android:singleLine="true"
android:textSize="14sp" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true">
<ImageView android:id="@+id/list_card_img" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:src="@drawable/near_card" />
<ImageView android:id="@+id/list_group_img" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/list_card_img" android:src="@drawable/near_group" />
<ImageView android:id="@+id/list_ticket_img" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/list_group_img" android:src="@drawable/near_ticket" />
</RelativeLayout>
</RelativeLayout>
第二種版面(list2)結構更簡單,把圖片放到右側、文字靠左,其餘邏輯相同,這裡省略。
最後别忘了在 onDestroy() 停止輪播,否則圖片會一直在背景換:
@Override
public void onDestroy() {
super.onDestroy();
if (mSliderLayout != null) {
mSliderLayout.stopAutoCycle();
mSliderLayout = null;
}
}
實際執行的效果如下圖,點選側滑選單的項目會切換主畫面的 Fragment,並自動收起選單:

把這個範例吃透,等於同時練會了 Fragment 溝通、異步網路、JSON 解析與 ListView 優化四件事,收穫相當划算。
如何解決 Android SDK Manager 下載速度太慢的問題
這個方法是在極客頭條上看到的,覺得相當實用,特別記錄下來以備日後不時之需。 當 Android SDK Manager 更新元件龜速爬行時,可以透過設定境內鏡像伺服器來大
一篇搞懂 Android 開發四大組件,外加 Intent 詳解
一篇帶你吃透 Android 四大組件 本文重點整理 Android 開發中的四大組件,主要分為: 一、Activity 詳解二、Service 詳解三、Broadcas
Android 座標系統全面詳解
座標系統的重要性自定義 View 的核心之一,是理解 Android 的座標系統。無論是排版、動畫、手勢或滑動,都離不開座標計算。螢幕區域Android 螢幕可區分為狀態
App 單頁最佳輸入框數量:鍵盤遮擋與表單體驗的設計判斷
App 單頁最佳輸入框數量 表單設計不能只看視覺,還要考慮鍵盤彈起後是否遮擋輸入框。原文以不同 iPhone 解析度估算單頁可容納的輸入框數量,並延伸到手機 App 的通