探究碎片Fragment(3)

我们来写一个简易版的新闻应用。这章使用 Kotlin 编写。实现在不同设备运行下展示不同效果

手机上运行时,点击标题打开新页面展示内容
在这里插入图片描述
平板运行时,点击标题,直接在右侧展示
在这里插入图片描述

1、MainActivity

class MainActivity : AppCompatActivity() {
   
    override fun onCreate(savedInstanceState: Bundle?) {
   
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

其中 activity_main 我们准备两个布局。分别在手机和平板上展示

下面这段代码表示在单页模式下只会加载一个新闻标题的 Fragment

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/newsTitle"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <fragment
        android:id="@+id/newsTitleFrag"
        android:name="com.xx.kotlinapplication.NewsTitleFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

接着创建一个 layout-sw600dp 文件夹,新建 activity_main.xml,双页模式下我们引入两个 Fragment,将新闻内容放在了 id 为 newsContentLayout 的布局下。因此找到这个 id 就是双页模式,否则就是单页。双页模式下左边放置新闻标题,右边放置新闻内容

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/newsTitle"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <fragment
        android:id="@+id/newsTitleFrag"
        android:name="com.xx.kotlinapplication.NewsTitleFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent" 
        android:layout_weight="1"/>
    
    <FrameLayout
        android:id="@+id/newsContentLayout"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3">
        <fragment
            android:id="@+id/newsContentFrag"
            android:name="com.xx.kotlinapplication.NewsContentFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </FrameLayout>
</LinearLayout>

2、创建显示新闻列表的布局 news_title_frag

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值