一、fragment的静态生成
第一步,main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<fragment
android:id="@+id/fragment1"
android:layout_width="match_parent"
android:layout_height="200dp"
android:name="com.example.fragment1demo.Fragment1"/>
<fragment
android:id="@+id/fragment2"
android:layout_width="match_parent"
android:layout_height="200dp"
android:name="com.example.fragment1demo.Fragment2"/>
</LinearLayout>
其中name对应于Fragment1和Fragment2两个.java文件。我的理解是调用了这两个文件里的onCreateView方法
第二步,Fragment1.java
public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1, null);
return view;
}
}
MainActivity.java
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Fragment1 fragment1 = new Fragment1();
Fragment2 fragment2 = new Fragment2();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
//把id为linearLayout的布局替换为fragment1
transaction.replace(android.R.id.content, fragment1);
//记得commit
transaction.commit();
}
}
三、Fragment生命周期
由于Fragment是依附于Activity上,所以其生命周期执行必然落后于Activity。
Activity:onCreate 创建时被调用
fragment:onattach
fragment:oncreate
fragment:oncreateView
fragment:onActivityCreated
Activity:onstart 用户可见时调用
fragment:onStart
Activity:onresume 获得焦点时调用
fragment:onResume
fragment:onPause
Activity:onpause 失去焦点时调用
fragment:onstop
Activity:onStop 界面消失时调用
fragment:ondestroyView
fragment:ondestroy
fragment:onDetach
Activity:onDestroy 销毁时调用
四、Fragment之间通讯
案例:通过Fragment1的Button来修改Fragment2的TextView
Fragment1.java
public class Fragment1 extends Fragment {
private Button button;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1, null);
button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Fragment2 fragment2 = (Fragment2) getActivity().getFragmentManager().findFragmentById(R.id.fragment2);
fragment2.setText("hello world");
}
});
return view;
}
}
两个Fragment通讯的桥梁是他们的Activity。通过该Activity来获得Fragment2的对象
public class Fragment2 extends Fragment {
private TextView tv;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment2, null);
tv = (TextView) view.findViewById(R.id.textView);
return view;
}
public void setText(String str){
tv.setText(str);
}
}
暴露出setText方法,在Fragment1.java中能进行调用