Fragment初识(一)

这里写图片描述
这里写图片描述
创建第一个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效果的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值