码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2014-05-13 13:29:41      阅读:413      评论:0      收藏:0      [点我收藏+]

标签:应用程序   ui   android   碎片   交互   

碎片之间进行交互


点击下载源码


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

bubuko.com,布布扣


Android学习笔记(十六)——碎片之间进行交互(附源码),布布扣,bubuko.com

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

标签:应用程序   ui   android   碎片   交互   

原文地址:http://blog.csdn.net/zenail501129/article/details/25653649

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!