Fragment的定义和解释这里就不说了,面试的时候也是经常问的到,官方的文档中是推荐和ViewPager一起使用,后期会继续介绍使用方法,但是我们也可以单独使用,会遇到一些小细节问题,如果不加注意会报错的。
1、XML布局文件中添加Fragment。每个Fragment其实类似与一个小型的Activity,所以有它对呀的java类。
public class Example extends Fragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.page1, null);
}
}
R.layout.page1对应的布局页面:
<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="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="这是一个Fragment" />
<Button
android:layout_