第四天 Fragment

自动生成文档

public class MyFragment extends Fragment {
    public MyFragment() {
        // Required empty public constructor
    }
    /**
     * 参数详解
     * fragment第一次创建用户界面时回调的方法
     * @param inflater 实体加载器,用于加载一个fragment的视图
     * @param container 表示当前fragment插入到activity中的对象
     * @param savedInstanceState  表示储存一个fragment的信息
     * @return
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_my, container, false);
    }
}
<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".fragment.MyFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />

</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <!--一定要注意的是:name属性是fragment的全限定名-->
    <fragment
        android:id="@+id/my_fragment_id"
        android:name="com.example.day004.fragment.MyFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </fragment>

</LinearLayout>

以上自动创建是静态创建fragment

动态创建 以及add,remove,replace,hide 方法

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //碎片管理器
        FragmentManager supportFragmentManager = getSupportFragmentManager();

        //开启事务
        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();

        FristFragment fristFragment = new FristFragment();
        fragmentTransaction.add(R.id.layout_content,fristFragment);

        //替换的方法
//        fragmentTransaction.replace(R.id.layout_content,new BlankFragment());

        //移除
//        fragmentTransaction.remove(fristFragment);

        //显示
//        fragmentTransaction.show(fristFragment);

        //隐藏
        fragmentTransaction.hide(fristFragment);

        //提交事务
        fragmentTransaction.commit();


    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值