Fragment使用(上),android基础开发入门

本文介绍了Android开发中Fragment的使用,包括动态添加、切换和Activity的生命周期关联。通过示例代码展示了如何创建和管理Fragment,以及在Activity中进行Fragment的替换操作。
摘要由CSDN通过智能技术生成

}

}

布局文件:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout

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=".fragment.Test1FragmentActivity">

<fragment

android:id="@+id/fragment_title"

android:layout_width=“match_parent”

android:layout_height=“50dp”

android:name=“com.gs.common3.fragment.TitleFragment”

/>

<fragment

android:id="@+id/fragment_content"

android:layout_width=“match_parent”

android:layout_height=“match_parent”

android:layout_below="@+id/fragment_title"

android:name=“com.gs.common3.fragment.ContentFragment”

/>

1.1.2、总结

1.2、Fragment动态应用


代码如下:

/**

  • 演示Fragment的动态使用

  • 案例效果:在Activity界面中有两个Fragment 标题和内容

*/

public class Test2FragmentActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_test2_fragment);

//1.创建Fragment的管理器对象;

FragmentManager manager = getFragmentManager();

//2.获取Fragment的事务对象并开启事务;

FragmentTransaction transaction = manager.beginTransaction();

//3.调用事务中相应的动态操作Fragment的方法执行;

transaction.add(R.id.title_layout, new TitleFragment());

transaction.add(R.id.content_layout, new ContentFragment());

//4.提交事务;

transaction.commit();

}

}

布局文件:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout

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=".fragment.Test2FragmentActivity">

<LinearLayout

android:id="@+id/title_layout"

android:layout_width=“match_parent”

android:layout_height=“50dp”

android:orientation=“vertical”>

<LinearLayout

android:id="@+id/content_layout"

android:layout_width=“match_parent”

android:layout_height=“match_parent”

android:orientation=“vertical”>

2、Fragment动态切换

==============

ShopRankFragment

public class ShopRankFragment extends Fragment {

@Nullable

@Override

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceSt
ate) {

return inflater.inflate(R.layout.fragment_shop_rank,null);

}

}

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout

xmlns:android=“http://schemas.android.com/apk/res/android”<

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值