您的位置:首页 > 移动开发 > Android开发

Android学习笔记(十六)——碎片之间进行交互(附源码)

2014-05-12 21:42 621 查看
碎片之间进行交互

点击下载源码

很多时候,一个活动中包含一个或者多个碎片,它们彼此协作,向用户展示一个一致的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的内容,说明获取成功~

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐