日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Kotlin?Fragment的具體使用詳解_Android

作者:知奕奕 ? 更新時間: 2022-11-21 編程語言

概念

fragment 可以用作一個 activity 內部的小分塊;

當我們從手機轉換到 pad 上時,整體界面會發生變化(比如由單列視圖變為雙列),此時就需要 fragment 的參與了!

基本示例

在本實例中,我們要制作一個雙列視圖,左右列均為 fragment 構成

設置左右列布局文件

新建布局文件 left_frag.xmlright_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 都需要一個單獨的類來對其頁面進行渲染,以及部分事件處理;

創建類 LeftFrag.kt

使該類繼承 Fragment,并實現方法,渲染 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 標簽,在 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>

這邊注冊完畢后就大功告成了,直接運行看看成果把!

原文鏈接:https://blog.csdn.net/delete_you/article/details/127186768

欄目分類
最近更新