編輯:關於 Android 程式設計
Fragment 與 Activity 之間的資料交換大致分為三種:一、Fragment 從 Activity 取得資料;二、Activity 從 Fragment 取得資料;三、Fragment 之間互相取得資料。本文聚焦第一種——Fragment 如何從 Activity 取得資料。
效果:Activity 將資料傳給兩個 Fragment,Fragment 取得後展示出來。

源碼:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout android:id="@+id/left"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="2"
android:background="#CCCCCC">
</LinearLayout>
<LinearLayout android:id="@+id/right"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="2">
</LinearLayout>
</LinearLayout>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
關鍵在於透過 Bundle 搭配 setArguments() 傳遞資料:
public class MainActivity extends Activity {
private FragmentManager manager;
private FragmentTransaction transaction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = getFragmentManager();
transaction = manager.beginTransaction();
MyFragment1 fragment1 = new MyFragment1();
Bundle bundle1 = new Bundle();
bundle1.putString("id", "Activity發送給MyFragment1的資料");
fragment1.setArguments(bundle1);
transaction.replace(R.id.left, fragment1, "left");
MyFragment2 fragment2 = new MyFragment2();
Bundle bundle2 = new Bundle();
bundle2.putString("id", "Activity發送給MyFragment2的資料");
fragment2.setArguments(bundle2);
transaction.replace(R.id.right, fragment2, "right");
transaction.commit();
}
}
public class MyFragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.f1, null);
TextView textView = (TextView) view.findViewById(R.id.textView);
Bundle bundle1 = getArguments();
textView.setText(bundle1.getString("id"));
return view;
}
}
核心機制:Activity 透過 setArguments() 將資料放入 Bundle,Fragment 則在 onCreateView() 中以 getArguments() 取出,即可完成資料傳遞。
Android App 整合 Mob 簡訊驗證碼:從申請到無 GUI 接入
為什麼選擇 Mob 簡訊驗證碼許多 App 在註冊、登入或通知時都需要簡訊能力。對個人開發者或小團隊而言,自行接電信服務成本較高,Mob 提供的簡訊驗證碼 SDK 是一個
Android 實作:將系統進程與使用者進程分開顯示
在前一篇《殺死使用者選取的進程並優化》中,我介紹了如何改善使用者體驗;本篇則接續說明如何把系統進程與使用者進程分離顯示。本文同樣以前一篇的基礎加以改進,建議先閱讀前一篇。
Android 原始碼剖析:Handler 與 Looper 訊息機制完整解說
Android 的應用程式與傳統 Java 程式一樣,靠訊息驅動運作。說得更具體些:系統維護一個訊息佇列,我們可以持續把訊息放進去,也可以從中取出來處理。擔起這份工作的三
借助 Android 自帶 VpnService 截取設備流量的原理與實踐
最近在做 Android 下的流量分析功能,查閱了大量資料。總結下來,在無需 Root 的前提下有兩種思路:一是設置代理來分析流量,二是使用 Android 系統提供的