Kotlin Fragment的具體使用詳解
概念
fragment 可以用作一個 activity 內(nèi)部的小分塊;
當(dāng)我們從手機轉(zhuǎn)換到 pad 上時,整體界面會發(fā)生變化(比如由單列視圖變?yōu)殡p列),此時就需要 fragment 的參與了!
基本示例
在本實例中,我們要制作一個雙列視圖,左右列均為 fragment 構(gòu)成
設(shè)置左右列布局文件
新建布局文件 left_frag.xml 和 right_frag.xml
左列布局我們插入一個按鈕并居中;
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/left_btn"
android:text="左邊的按鈕"
android:layout_gravity="center_horizontal"/>
</LinearLayout>右列布局我們則插入一個文本;
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/right_text"
android:text="右邊的frag"
android:layout_gravity="center_horizontal"/>
</LinearLayout>配置左右布局類
一般的,所有 fragment 都需要一個單獨的類來對其頁面進行渲染,以及部分事件處理;
創(chuàng)建類 LeftFrag.kt
使該類繼承 Fragment,并實現(xiàn)方法,渲染 fragment:
這里使用了 inflater 對頁面進行注冊;
package com.zhiyiyi.listviewdemo
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
class LeftFrag : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.left_frag, container, false)
}
}主布局文件注冊
我們需要在主 activity 的布局文件中使用這兩個 fragment;
直接添加兩個 fragment 標(biāo)簽,在 name 屬性寫上 fragment 布局處理的類即可;
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/leftfrag"
android:name="com.zhiyiyi.listviewdemo.LeftFrag"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="@+id/rightfrag"
android:name="com.zhiyiyi.listviewdemo.RightFrag"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>這邊注冊完畢后就大功告成了,直接運行看看成果把!
到此這篇關(guān)于Kotlin Fragment的具體使用詳解的文章就介紹到這了,更多相關(guān)Kotlin Fragment內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android對話框AlertDialog與DatePickerDialog及TimePickerDialog使用詳解
這篇文章主要介紹了Android對話框中的提醒對話框AlertDialog、日期對話框DatePickerDialog、時間對話框TimePickerDialog使用方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-09-09
Android 6.0 掃描不到 Ble 設(shè)備需開啟位置權(quán)限的方法
今天小編就為大家分享一篇Android 6.0 掃描不到 Ble 設(shè)備需開啟位置權(quán)限的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07

