**碎片之間進行交互**
**[點擊下載源碼](http://download.csdn.net/detail/u012904198/7337195)**
很多時候,一個活動中包含一個或者多個碎片,它們彼此協作,向用戶展示一個一致的UI。在這種情況下,碎片之間能進行通信并交換數據十分重要。
1、使用上一篇中創建的同一個項目,在fragment.xml中添加TextView的標識id:
~~~
android:id="@+id/lblFragment1"
~~~
2、在fragment2.xml中添加一個Button,用于與fragment1進行交互:
~~~
<Button
android:id="@+id/btnGetText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get text in Fragment #1"
android:textColor="#000000" />
~~~
3、將兩個碎片重新添加到main.xml中:
~~~
<fragment
android:id="@+id/fragment1"
android:name="net.zenail.Fragments.Fragment1"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="@+id/fragment2"
android:name="net.zenail.Fragments.Fragment2"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1" />
~~~
4、在FragmentsActivity.java中,注釋掉上一篇中添加的代碼,修改后如下:
~~~
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
//
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
if (display.getWidth() > display.getHeight()) {
//
Fragment1 fragment1 = new Fragment1();
fragmentTransaction.replace(android.R.id.content, fragment1);
} else {
//
Fragment2 fragment2 = new Fragment2();
fragmentTransaction.replace(android.R.id.content, fragment2);
}
fragmentTransaction.commit();
*/
}
~~~
5、在Fragment2.java中添加如下代碼,實現與Fragment1的交互:
~~~
@Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
Button btnGetText = (Button) getActivity()
.findViewById(R.id.btnGetText);
btnGetText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
TextView lbl = (TextView) getActivity().findViewById(
R.id.lblFragment1);//通過getActivity()方法獲得當前嵌入了該碎片的活動,再使用findViewById()定位該碎片中包含的視圖
Toast.makeText(getActivity(), lbl.getText(), Toast.LENGTH_SHORT)
.show();
}
});
}
~~~
6、按F11調試應用程序,在右側的第二個碎片中單擊按鈕,可以看到彈出一個消息框,內容正是碎片1中TextView的內容,說明獲取成功~

- 前言
- Android應用程序剖析
- (一)——生命周期
- (二)——使用Intent傳數據之通用方式
- (三)——使用靜態變量傳遞數據
- (四)——通過剪切板傳遞數據
- (五)——通過全局變量傳遞數據
- (六)——從Activity返回數據
- adt-bundle-linux-x86_64-20131030下新建工程提示找不到adb和R.java問題的解決
- Eclipse啟動時提示fail to create the Java Virtual Machine問題的解決
- Android常見UI組件之ListView(一)
- Android常見UI組件之ListView(二)——定制ListView
- (七)——顯示對話框窗口
- (八)——顯示進度對話框
- (九)——更復雜的進度對話框
- (十)——使用意圖鏈接活動
- (十一)——從意圖返回結果
- (十二)——使用意圖傳遞數據的幾種方式
- (十三)——碎片(一)
- (十四)——在運行時添加碎片(附源碼)
- (十五)——碎片的生命周期(附源碼)
- (十六)——碎片之間進行交互(附源碼)
- (十七)——使用意圖調用內置應用程序
- (十八)——使用意圖篩選器和實現瀏覽網頁(附源碼)