创建第一个fragment
name属性:必须填写完整的路径,即包括,包名和类名
fragment重写onCreateView()方法在这个方法中给Fragment添加布局
1.创建一个fragment叫做MyFragment
MyFragment会重写一个本身的无参构造方法,并且自动生成一个onCreateView方法,返回的是自己默认生成的xml路径
public class MyFragment extends Fragment {
public MyFragment() {
// Required empty public constructor
}
//给fragment设置布局
//相当于activity的 setContentView(R.layout.activity_main);
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_my, container, false);
}
}
fragment的布局代码
<FrameLayout 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:background="#00cacb"
tools:context="com.axnet.fragmentandviewpager.MyFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="这是一个fragment"/>
</FrameLayout>
在mainActivity中引入这个fragment
注意name必须填写完整的路径,即包括,包名和类名,当然可以快捷方式生成然后自己选择
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp"
tools:context="com.axnet.fragmentandviewpager.MainActivity">
<fragment
android:name="com.axnet.fragmentandviewpager.MyFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fragment"
/>
</RelativeLayout>
我们这是个背景变了个颜色,方便观看,并且设置了一个padding为20
继承自AppCompatActivity
继承自FragmentActivity
fragment是3.0以后才添加的功能,
直接继承自Activity的话会报错,继承继承activity的其他activity不会崩溃
上图的效果表示,AppCompatActivity默认是在toolBar效果的