編輯:關於 Android 程式設計
本文把 Fragment 互跳時的兩個核心問題一次講完:怎麼把參數送過去,以及怎麼把使用者的選擇帶回來。
示範的互動流程是:
1、在 Fragment1 點擊「載入第二個 Fragment 按鈕」,堆疊 Fragment2,同時把一段字串傳過去;
2、在 Fragment2 點選任一張圖片,把結果回傳 Fragment1,並在第一頁顯示出來。
垂直排列,上方一個 ImageView 用來呈現回傳的圖片,下方一個 Button 用來載入第二頁。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical">
<ImageView android:id="@+id/img_result"
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="center"/>
<Button android:id="@+id/load_fragment2_btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="載入第二個Fragment"/>
</LinearLayout>
上方 TextView 顯示傳過來的字串,下方四張圖供點選。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical">
<TextView android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is fragment 2"
android:textColor="#000000"
android:textSize="25sp" />
<ImageView android:id="@+id/img1" android:layout_width="100dip"
android:layout_height="100dp" android:scaleType="center" android:src="@drawable/animal1"/>
<ImageView android:id="@+id/img2" android:layout_width="100dip"
android:layout_height="100dp" android:scaleType="center" android:src="@drawable/animal2"/>
<ImageView android:id="@+id/img3" android:layout_width="100dip"
android:layout_height="100dp" android:scaleType="center" android:src="@drawable/animal3"/>
<ImageView android:id="@+id/img4" android:layout_width="100dip"
android:layout_height="100dp" android:scaleType="center" android:src="@drawable/animal4"/>
</LinearLayout>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Fragment1 fragment1 = new Fragment1();
getFragmentManager().beginTransaction()
.replace(R.id.main_layout, fragment1)
.commit();
}
}
public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1, container, false);
Button btn = (Button) view.findViewById(R.id.load_fragment2_btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
Fragment2 fragment2 = new Fragment2();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.main_layout, fragment2);
transaction.addToBackStack(null);
transaction.commit();
}
});
return view;
}
}
這一步刻意先不做任何傳參,確保骨架能跑起來,後面再逐步加上去,出問題時比較好定位。
為什麼不寫有參數的建構子,可以參考我另一篇〈為什麼要用 Fragment.setArguments(Bundle bundle) 來傳遞參數〉的源碼分析,這裡只講實務怎麼寫。
在 Fragment2 中開一個靜態工廠方法接收參數:
public static Fragment2 newInstance(String text) {
Fragment2 fragment = new Fragment2();
Bundle args = new Bundle();
args.putString("param", text);
fragment.setArguments(args);
return fragment;
}
在 onCreateView 中把值取出來塞進 TextView:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment2, container, false);
if (getArguments() != null) {
String mParam1 = getArguments().getString("param");
TextView tv = (TextView) view.findViewById(R.id.textview);
tv.setText(mParam1);
}
return view;
}
呼叫端只要改一行,把 new Fragment2() 換成工廠方法:
public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1, container, false);
Button btn = (Button) view.findViewById(R.id.load_fragment2_btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
Fragment2 fragment2 = Fragment2.newInstance("從 Fragment1 傳來的參數");
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.main_layout, fragment2);
transaction.addToBackStack(null);
transaction.commit();
}
});
return view;
}
}
參數要往回傳,就不能靠建構子了,得用回呼介面。做法與自訂 Dialog 的回傳機制完全一樣:在被呼叫方宣告介面,由呼叫方傳入匿名實作。
public class Fragment2 extends Fragment implements View.OnClickListener {
// 對外宣告的回呼介面
public interface OnItemSelectedListener {
void onItemSelected(int drawableId);
}
private OnItemSelectedListener mListener;
private String mParam;
public static Fragment2 newInstance(String text, OnItemSelectedListener listener) {
Fragment2 fragment = new Fragment2();
Bundle args = new Bundle();
args.putString("param", text);
fragment.setArguments(args);
fragment.mListener = listener;
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment2, container, false);
if (getArguments() != null) {
mParam = getArguments().getString("param");
TextView tv = (TextView) view.findViewById(R.id.textview);
tv.setText(mParam);
}
view.findViewById(R.id.img1).setOnClickListener(this);
view.findViewById(R.id.img2).setOnClickListener(this);
view.findViewById(R.id.img3).setOnClickListener(this);
view.findViewById(R.id.img4).setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
int drawableID = -1;
switch (v.getId()) {
case R.id.img1: drawableID = R.drawable.animal1; break;
case R.id.img2: drawableID = R.drawable.animal2; break;
case R.id.img3: drawableID = R.drawable.animal3; break;
case R.id.img4: drawableID = R.drawable.animal4; break;
}
if (drawableID != -1 && mListener != null) {
mListener.onItemSelected(drawableID);
}
// 回到上一頁
getFragmentManager().popBackStack();
}
}
Fragment1 這邊在建立 Fragment2 時把回呼實作一起傳進去,收到結果就更新自己的 UI:
Fragment2 fragment2 = Fragment2.newInstance("從 Fragment1 傳來的參數",
new Fragment2.OnItemSelectedListener() {
@Override
public void onItemSelected(int drawableId) {
ImageView imageView = (ImageView) getActivity().findViewById(R.id.img_result);
imageView.setImageDrawable(getResources().getDrawable(drawableId));
}
});
getFragmentManager().beginTransaction()
.add(R.id.main_layout, fragment2)
.addToBackStack(null)
.commit();
小提醒:回呼裡若要更新 Fragment1 的 View,記得確認 Fragment1 此時處於 RESUMED 狀態,並做好空值與生命週期檢查,否則在背景被回收後回來容易踩到 NullPointerException。若你的專案已導入 ViewModel,把結果放進共享的 ViewModel 再由 Fragment1 觀察,會比回呼更耐得住設定變更。
ART 世界探險(18):InlineMethod 方法內聯剖析
好,我們還是先復習一下上上節學到的那張圖: 在正式進入 InlineMethod 之前,我們再補充一點 BasicBlock 的知識。 BasicBlock 中針對 M
Android 打飛機遊戲實戰:無限滾動的背景圖(2)
先來盤點一下遊戲畫面裡會出現的元素:可無限滾動的背景、可操作的主角、主角的子彈、主角的血量、兩種怪物(敵機),還有一個 Boss 以及 Boss 的爆炸效果。本篇先從最基
Android 圖形變換特效详解:Matrix 矩陣原理與實作(四)
今天我們來談談 Android 圖片變形的特效。上一講我們談的是透過 ColorMatrix 類實現的色彩特效,主要透過色彩矩陣的係數與每個像素點對應的顏色偏移量來改變顏
百度地圖圖層玩法:普通圖、衛星圖、實時路況與城市熱力圖
一張地圖不只有「地圖」這一種樣貌。切換衛星影像、疊加實時路況、顯示城市熱力分布——這些效果在百度地圖 Android SDK 裡都只要一行屬性設定就能搞定。本文帶你看懂