如何创建fragment
时间: 2024-05-12 08:19:33 浏览: 51
要创建一个fragment,可以按照以下步骤:
1. 在Android Studio中创建一个新的项目,选择“Empty Activity”模板。
2. 打开res文件夹,右键点击layout文件夹,选择“New” -> “Fragment” -> “Fragment (Blank)”。
3. 在弹出的对话框中,输入fragment的名称,点击“Finish”按钮。
4. 在创建的fragment布局文件中,添加你想要显示的UI组件和布局。
5. 在创建的fragment类中,继承自Fragment或其子类,并在onCreateView()方法中加载布局文件。
6. 在需要使用fragment的activity中,使用FragmentManager将fragment添加到activity中。
例如,以下是一个简单的fragment类:
```
public class MyFragment extends Fragment {
@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);
}
}
```
在activity中添加fragment的示例代码:
```
MyFragment fragment = new MyFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_container, fragment);
transaction.commit();
```
其中,R.id.fragment_container是一个FrameLayout,用于容纳fragment的视图。