Android应用开发中Fragment与Activity间通信示例讲解

2019-12-10 19:01:42王旭

通过这种方法来得到fragment上面的控件

5.activity_fragment.xml里面的代码是这个样子的

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://www.easck.com/apk/res/android"
 android:id="@+id/main_layout"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:baselineAligned="false"
 android:orientation="horizontal" >
 <fragment
 android:id="@+id/fragment1"
 android:name="lgx.fram.framents.Fragment1"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_weight="1" />
 <fragment
 android:id="@+id/fragment2"
 android:name="lgx.fram.framents.Fragment2"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_weight="1" />
</LinearLayout>

注意:控件fragment里的android:name=" "里面填写的是你的Fragment类的绝对路径(脑子突然短路,是这样说的吗??),id用来标示fragment。

6.FragmentActivity是最简单的,就只是setContentView,并没有进行其他改变。看下面

package lgx.fram.framents;

import android.app.Activity;
import android.os.Bundle;


public class FragmentActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_fragment);
 }

}

在这里我的整个小应用就做完了。我这里的Fragment通过布局文件加入到Activity里的,还有另一种方式是通过编程的方式将Fragment加入Activity里。这里我简单叙述

上面的1,2,3,4都不需要动。

第5步骤,activity_fragment.xml里面的代码变成下面的