activity_main.xml作为主Activity的布局文件,在里面加入两个Fragment的引用,使用android:name前缀来引用具体的Fragment:
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
android:id="@+id/fragment1"
android:name="com.example.myapplication5.BlankFragment"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1"/>
android:id="@+id/fragment2"
android:name="com.example.myapplication5.BlankFragment2"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1"/>
最后打开或新建MainActivity作为程序的主Activity,里面的代码非常简单,都是自动生成的:
publicclassMainActivityextendsAppCompatActivity{
@Override
protectedvoidonCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
接着把上边XML中的Fragment创建一下 并在里面写一个Textview可以让我们进行访问
Fragment1 代码
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BlankFragment">
android:id="@+id/fragment1_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is fragment 1"
android:textColor="#000000"
android:textSize="25sp"/>
JAVA 中代码 可以看到并没有变动
publicclassBlankFragmentextendsFragment{
publicBlankFragment(){
// Required empty public constructor
}
@Override
publicViewonCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
// Inflate the layout for this fragment
returninflater.inflate(R.layout.fragment_blank, container,false);
}
}
接下来我们去写Fragment2的代码 还是一样 敲了一个个Button进行演示
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BlankFragment2">
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get fragment1 text"
/>
接着打开Fragment2.java,添加onActivityCreated方法,并处理按钮的点击事件:
publicclassBlankFragment2extendsFragment{
privateView inflate;
publicBlankFragment2(){
// Required empty public constructor
}
@Override
publicViewonCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
// Inflate the layout for this fragment
inflate = inflater.inflate(R.layout.fragment_blank_fragment2, container,false);
returninflate;
}
@Override
publicvoidonActivityCreated(@Nullable Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
Button button = (Button) getActivity().findViewById(R.id.button);
button.setOnClickListener(newView.OnClickListener() {
@Override
publicvoidonClick(View v){
TextView textView = (TextView) getActivity().findViewById(R.id.fragment1_text);
Toast.makeText(getActivity(), textView.getText(), Toast.LENGTH_LONG).show();
}
});
}
}