fragment入门

时间:2023-03-09 07:45:40
fragment入门

[1]在activity布局中定义fragment

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.itheima.fragment.Fragment1"
android:id="@+id/list"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment android:name="com.itheima.fragment.Fragment2"
android:id="@+id/viewer"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>

[2]声明fragment

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; //定义一个Fragment
public class Fragment1 extends Fragment { //当用户第一次画ui的时候调用 要显示Fragment自己的内容 setContentView(R.layout.activity_main);
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//[1]通过打气筒把一个布局转换成view对象
View view = inflater.inflate(R.layout.fragment1, null); return view;
}
}

[3]name属性 要指定我们自己定义的fragment