首先新建一个fragment的布局文件,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<Button
android:id="@+id/btnLeftFrag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button in left fragment" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<Button
android:id="@+id/btnLeftFrag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button in left fragment" />
</LinearLayout>
然后在新建控制该fragment的类,该类继承自Fragment。
package com.example.flypie.notesbook.Fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.flypie.notesbook.R;
/**
* Created by FLYPIE on 2015/12/11.
*/
public class LeftFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.left_fragment,container,false);
return view;
}
}
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.flypie.notesbook.R;
/**
* Created by FLYPIE on 2015/12/11.
*/
public class LeftFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.left_fragment,container,false);
return view;
}
}
在需要使用该fragment的布局中加入
<fragment
android:id="@+id/fragLeft"
android:name="com.example.flypie.notesbook.Fragment.LeftFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="@+id/fragLeft"
android:name="com.example.flypie.notesbook.Fragment.LeftFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
tools:layout="@layout/left_fragment" />
注意:加载布局时会执行android:name指定的类
Fragment与所在Activity之间通信:
在Activity中可以通过以下方法更改不同的Fragment:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.rightLayout,anotherRightFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
注意:其中的R.id.rightLayout是包含当前要更换的fragment的容器
在Fragment中可以通过以下方法获取所在Activity的实例,进而调用其方法:
TestFragmentActivity testFragmentActivity = (TestFragmentActivity) getActivity();
可以通过调用Activity的以下方法获取指定的fragment的实例,进而调用其方法:
RightFragment rightFragment = (RightFragment) testFragmentActivity.getFragmentManager().findFragmentById(R.id.fragRight);