我们来写一个简易版的新闻应用。这章使用 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