編輯:關於 Android 程式設計
前置說明一:照前面的方式建立專案時,如果用的是較新的 ADT,而 Minimum SDK 選了 Android 2.* 或 1.*,系統會自動產生一個相容用的附屬專案 appcompat_v7。這個專案不能刪,刪掉會報錯。
前置說明二:專案建立好之後,layout 資料夾中會預設有兩個檔案:activity 與 fragment 各一。

Fragment 直譯為「碎片、片段」,說白了就是一個可重複使用的模組。它的價值在於把「畫面的一部分」抽成獨立元件,讓同一塊 UI 能在不同 Activity 之間共用,也讓平板與手機能共用同一套邏輯。
可以這樣理解 Fragment 與 Activity 的關係:
Fragment 可以被多個 Activity 重用,它有自己的生命週期與版面,但必須依附在一個 Activity 之上才能顯示。Fragment 有自己的 onCreateView() 來產生自己的檢視,而 Activity 則負責決定「要把哪個 Fragment 放在畫面的哪個位置」。

fragment_main.xml:一個文字與兩個按鈕。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.javen.xresource.activity.fragment.MainFragment" >
<TextView
android:id="@+id/ftxv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/fragment" />
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/change_fragment" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/change_activity" />
</LinearLayout>
activity_main.xml:自己有一個文字,並用 <fragment> 標籤把 Fragment 嵌進來。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.javen.xresource.activity.MainActivity"
tools:ignore="MergeRootFrame">
<TextView
android:id="@+id/atxv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/activity" />
<!-- 以 XML 方式在 Activity 中嵌入 Fragment -->
<fragment
android:name="com.javen.xresource.activity.fragment.MainFragment"
android:id="@+id/mft"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
繼承 Fragment,重點在覆寫 onCreateView():用 inflater 把版面攤開成 View 並回傳。要注意的是,findViewById 必須在這裡產生的 rootView 上呼叫,而不是直接呼叫 Fragment 自己的方法。
package com.javen.xresource.activity.fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.javen.xresource.activity.R;
public class MainFragment extends Fragment {
private TextView fragmentTextView;
private Button button;
public MainFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// 使用 fragment_main.xml 初始化 Fragment
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// 注意:要在 rootView 上找元件
button = (Button) rootView.findViewById(R.id.btn);
fragmentTextView = (TextView) rootView.findViewById(R.id.ftxv);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
fragmentTextView.setText("我被 fragment 點擊了...");
}
});
return rootView;
}
}
這樣 Fragment 部分就完成了。
package com.javen.xresource.activity;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button button;
private TextView activityTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* 也可以用 Java 程式碼嵌入 Fragment,效果與 XML 方式相同:
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new MainFragment())
.commit();
}
*/
activityTextView = (TextView) findViewById(R.id.atxv);
// 取得 Activity 中的 Fragment
Fragment fragment = getFragmentManager().findFragmentById(R.id.mft);
// 取得 Fragment 中的 Button2
button = (Button) fragment.getView().findViewById(R.id.btn2);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
activityTextView.setText("我被 activity 點擊了...");
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
執行專案即可看到效果:Fragment 內的按鈕控制 Fragment 自己的文字,Activity 內取得的按鈕則控制 Activity 的文字。
衍生出的問題是:Fragment 能不能與 Activity 通訊?答案是能,但方式有講究。
直覺上會想用:
getActivity().findViewById(R.id.atxv);
但實測這行會回傳 null,取不到 Activity 中的 View 元素。所以 Button2 的操作只能寫在 Activity 裡。
為什麼會這樣?有兩個層次的原因。
技術層面:Fragment 的 onCreateView() 執行時,Activity 的 setContentView() 已經跑完,atxv 理應存在。回傳 null 通常是時序問題——若這行被放在 Fragment 初始化階段執行,Activity 的版面尚未就緒。此外 R.id.atxv 這個 ID 必須確實存在於當前的版面樹中。
設計層面:更重要的一點是,Fragment 直接伸手去拿 Activity 的 View,本身就是不好的設計。這會讓 Fragment 與特定 Activity 的版面緊密耦合,重用性蕩然無存。正確做法是把溝通抽象成介面:
public class MainFragment extends Fragment {
/** Activity 要實作這個介面 */
public interface OnFragmentInteractionListener {
void onBtn2Clicked();
}
private OnFragmentInteractionListener mListener;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " 必須實作 OnFragmentInteractionListener");
}
}
// 在 Fragment 內觸發,交由 Activity 決定要做什麼
private void notifyActivity() {
if (mListener != null) {
mListener.onBtn2Clicked();
}
}
}
反過來,Activity 要操作 Fragment 時,則透過 Fragment 自己開放的公開方法,或直接呼叫 FragmentTransaction 的 API。
一句話總結:Fragment 之間、Fragment 與 Activity 之間的溝通,應該走「介面回呼」而非「直接抓對方的 View」。這個原則在後續使用 ViewModel 或 LiveData 的架構中會變得更清楚——資料狀態放在共用元件裡,雙方各自訂閱變化,耦合度降到最低。
Swift 錯誤處理魔法課:可空、guard、自定義錯誤與 defer
Swift 錯誤處理的起點 Swift 的錯誤處理從早期版本一路演進,到 Swift 2 之後,逐漸強調可恢復錯誤、可空型別與 guard 語句的組合使用。良好的錯誤處理
Android 模擬器 2.0 初探:更快、更強、更自由
我相信,每一位安卓開發者都會同意:2015 年安卓開發者大會上最重磅的消息,就是 Android Studio 2.0 與安卓模擬器 2.0。官方宣稱,新模擬器在運行與部
在 Android Studio 中正確設定 NDK 與 JNI 開發環境
Ps:最近比較閒,就多寫幾篇當作整理。順便說一句,實在不太欣賞那種直接搬網路文章上來、自己完全沒跑過一遍的寫法——結果就是網路上的教學千篇一律,最初那個人踩過的坑,後面每
Android 四大組件之 Service 服務詳解(上)
一、Service 是什麼 Service 是 Android 四大組件之一(Activity、Service、BroadcastReceiver、ContentProv