fragment 简单的例子

fragment是什么呢 fragment相当于一块画布 可以根据要求在fragment更改界面 就是说不换activity的情况下把局部布局给改了
下面用实例来说明
当我点击FRAFMENT1时界面是这样的
这里写图片描述
当我点击FRAFMENT2时界面是这样的
这里写图片描述
这是最基础的fragment的应用
接下来看下我的布局(activity_main.xml 和fragment1和fragment1)

activity_main

<?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:layout_height="match_parent"
    tools:context="com.example.shinelon.fragment.MainActivity"
    android:orientation="vertical">

   <LinearLayout
       android:id="@+id/layout"
       android:layout_width="match_parent"
       android:layout_height="300dp"
       android:orientation="vertical"></LinearLayout>
    <Button
        android:layout_width="wrap_content"
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单Fragment使用例子: 1. 创建一个MyFragment类,继承Fragment类,并实现onCreateView方法: ``` public class MyFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_my, container, false); return view; } } ``` 2. 在res目录下创建一个fragment_my.xml布局文件,用于定义Fragment的UI界面: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is my fragment."/> </LinearLayout> ``` 3. 在MainActivity中添加Fragment,并将其显示出来: ``` public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 添加Fragment FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); MyFragment fragment = new MyFragment(); transaction.add(R.id.fragment_container, fragment); transaction.commit(); } } ``` 4. 在activity_main.xml布局文件中,添加一个FrameLayout作为Fragment的容器: ``` <FrameLayout android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" /> ``` 通过以上步骤,就可以将MyFragment添加到MainActivity中,并在UI界面上展示出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值