編輯:關於 Android 程式設計
Fragment 有兩種典型的使用方式:靜態方式(寫在版面 XML 裡)與動態方式(在程式碼中用 FragmentTransaction 掛載)。本文先後示範這兩條路徑,再進一步說明如何用 PreferenceFragment 做出一個功能完整的設定頁面。
public class ExampleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.example_fragment, container, false);
}
}
<?xml version="1.0" encoding="utf-8"?>
<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="horizontal" >
<EditText
android:id="@+id/edit_message"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="@string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" />
</LinearLayout>
public class FragmentLayoutTest extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/fragment_intro" />
<fragment
android:name="com.skw.fragmentlayouttest.ExampleFragment"
android:id="@+id/frag_example"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
透過 <fragment> 標籤的 android:name,Fragment 會在 Activity 版面 inflate 時一併建立。這種寫法簡單,但缺點是執行期無法移除或替換。
Fragment 子類與版面沿用上面的內容,差別在第三步之後。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/fragment_intro" />
<FrameLayout
android:id="@+id/frag_example"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
public class FragmentLayoutTest extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.frag_example, fragment);
fragmentTransaction.commit();
}
}
動態方式的好處是可以在執行期任意 add、replace、remove,並搭配 addToBackStack() 支援返回鍵。
<PreferenceScreen xmlns:android="https://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="PreferenceCategory A">
<!--
(01) android:key 是 Preference 的 id,也是唯一識別
(02) android:title 是主標題
(03) android:summary 是副標題
-->
<CheckBoxPreference
android:key="checkbox_preference"
android:title="title_checkbox_preference"
android:summary="summary_checkbox_preference" />
</PreferenceCategory>
<PreferenceCategory android:title="PreferenceCategory B">
<!-- android:dialogTitle 是對話框標題;android:defaultValue 是預設值 -->
<EditTextPreference
android:key="edittext_preference"
android:title="title_edittext_preference"
android:summary="null"
android:dialogTitle="dialog_title_edittext_preference"
android:defaultValue="null" />
<!-- android:entries 是選項說明;android:entryValues 是選項值 -->
<ListPreference
android:key="list_preference"
android:dialogTitle="Choose font"
android:entries="@array/pref_font_types"
android:entryValues="@array/pref_font_types_values"
android:summary="sans"
android:title="Font"
android:defaultValue="sans"/>
</PreferenceCategory>
<PreferenceCategory android:title="PreferenceCategory C">
<SwitchPreference
android:key="switch_preferece"
android:title="title_switch_preferece"
android:defaultValue="true" />
<SeekBarPreference
android:key="seekbar_preference"
android:title="title_seekbar_preference"
android:max="100"
android:defaultValue="30" />
</PreferenceCategory>
</PreferenceScreen>
PreferenceFragment 可用的元件相當豐富,除了上面用到的,還有 VolumePreference 等。共同屬性整理如下:
android:key:Preference 的 id,唯一識別。android:title:主標題。android:summary:副標題。android:dialogTitle:彈出對話框的標題。android:defaultValue:預設值。android:entries:清單中各選項的說明文字。android:entryValues:清單中各選項對應的值。版本注意:SwitchPreference 是 API 14(Android 4.0)才支援的,若要使用,必須在 manifest 中宣告最低支援版本:
<uses-sdk android:minSdkVersion="14" />
public class PrefsFragment extends PreferenceFragment
implements SharedPreferences.OnSharedPreferenceChangeListener,
Preference.OnPreferenceClickListener {
private static final String TAG = "##PrefsFragment##";
private static final String CHECK_PREFERENCE = "checkbox_preference";
private static final String EDITTEXT_PREFERENCE = "edittext_preference";
private static final String LIST_PREFERENCE = "list_preference";
private static final String SWITCH_PREFERENCE = "switch_preferece";
private static final String SEEKBAR_PREFERENCE = "seekbar_preference";
private Preference mEditText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
mEditText = (Preference) findPreference(EDITTEXT_PREFERENCE);
mEditText.setOnPreferenceClickListener(this);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference connectionPref = findPreference(key);
if (key.equals(CHECK_PREFERENCE)) {
boolean checked = sharedPreferences.getBoolean(key, false);
Log.d(TAG, "CheckBox: checked=" + checked);
} else if (key.equals(EDITTEXT_PREFERENCE)) {
String value = sharedPreferences.getString(key, "");
connectionPref.setSummary(value);
Log.d(TAG, "EditText: value=" + value);
} else if (key.equals(LIST_PREFERENCE)) {
String value = sharedPreferences.getString(key, "");
connectionPref.setSummary(value);
Log.d(TAG, "List: value=" + value);
} else if (key.equals(SWITCH_PREFERENCE)) {
boolean checked = sharedPreferences.getBoolean(key, false);
Log.d(TAG, "Switch: checked=" + checked);
} else if (key.equals(SEEKBAR_PREFERENCE)) {
int value = sharedPreferences.getInt(key, 0);
Log.d(TAG, "Seekbar: value=" + value);
}
}
@Override
public boolean onPreferenceClick(Preference preference) {
SharedPreferences sharedPreferences = preference.getSharedPreferences();
String value = sharedPreferences.getString(preference.getKey(), "");
Log.d(TAG, "onPreferenceClick: value=" + value);
return true;
}
@Override
public void onResume() {
super.onResume();
getPreferenceManager().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onPause() {
getPreferenceManager().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
}
要理解這段程式碼,先記住一個觀念:PreferenceFragment 中的每一項設定,本質上都是一個 SharedPreferences 項目,會存在該 APK 的私有資料區。監聽變化的方式主要有兩種:
SharedPreferences.OnSharedPreferenceChangeListener,在 onSharedPreferenceChanged() 中依 key 分別處理。別忘了在 onResume() 註冊、onPause() 取消註冊,否則容易造成記憶體洩漏。Preference.OnPreferenceClickListener,用來攔截特定項目的點擊行為(例如做一個「清除快取」的入口)。 public class FragmentTest extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new PrefsFragment())
.commit();
}
}
這裡直接把 Fragment 掛到 android.R.id.content,也就是整個視窗的內容區,因此不必另外準備版面檔——這是快速做出一個獨立設定頁的簡便寫法。
用 RadioGroup 與 RadioButton 實作單選與預設選中
本文將透過 RadioGroup 搭配 RadioButton 來實作「組內單選」。所謂 RadioGroup,就是把多個 RadioButton 進行分組,讓它們能被統
Android 毛玻璃效果側滑菜單實作
實現目標 毛玻璃效果(也稱高斯模糊)的原理是:把背後的畫面模糊化並降低不透明度,看起來就像隔著一層磨砂玻璃。效果圖如下: 它本質上是「透明 + 背景高斯模糊」。這套做法
Android開發環境怎麼搭?JDK、SDK、Eclipse 與 ADT 的安裝流程
隨著手機使用者增加,安卓的軟體生態持續擴張——遊戲、工具、系統客製都需要人做。對想投入 Android 開發的人來說,第一道門檻不是語法,而是把開發環境正確架起來。需要準
打造支援任意 View 的通用下拉刷新控件
下拉刷新幾乎是每個 App 必備的功能。早期多數人使用的是 chrisbanes 的 PullToRefresh,或修改自該框架的其他庫;如今選擇已相當多元,GitHub