Kotlin获取Fragment中的组件

左边和右边分别是两个不同的Fragment,左边的Fragment中右一个Button组件,目标是想要获取这个组件的id,以便进行将右边的Fragment更改成另一个Fragmeent的操作。

left_fragment.xml

xml 复制代码
<?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"
    android:orientation="vertical">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Button"
        />
</LinearLayout>

LeftFragment.kt

kotlin 复制代码
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment

class LeftFragment : Fragment() {
    override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.left_fragment, container, false)
    }
}

activity_main.xml

xml 复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="horizontal">

    <fragment
        android:id="@+id/leftFragment"
        android:name="com.example.fragmenttest.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        />

    <fragment
        android:id="@+id/rightLayput"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        />

</LinearLayout>

可以看到,通过findViewById的方式来获取肯定是失败的

以前以通过kotlin-android-extensions这个插件,可以直接使用布局中的控件id来操作view控件, 不用再findViewById。但是很可惜,在as升级到4.0之后便被抛弃了。

现在通过MainBingding也可以实现,首先在app下的build.gradle文件下面添加如下代码:

xml 复制代码
android{
...
    buildFeatures{
        viewBinding true
    }
 }

将上述代码报错修改成如下图所示的代码即可:

获取到后成功修改:

ps:

绑定的书写:

例如news_content_frag.xml需要绑定,那么写法如下:

kotlin 复制代码
val binding = NewsContentFragBinding.inflate(layoutInflater)
相关推荐
aqi001 分钟前
FFmpeg开发笔记(七十七)Android的开源音视频剪辑框架RxFFmpeg
android·ffmpeg·音视频·流媒体
泓博16 分钟前
Objective-c把字符解析成字典
开发语言·ios·objective-c
try2find19 分钟前
安装llama-cpp-python踩坑记
开发语言·python·llama
番茄小能手1 小时前
【全网唯一】C# 纯本地离线文字识别Windows版dll插件
开发语言·c#
梁诚斌1 小时前
使用OpenSSL接口读取pem编码格式文件中的证书
开发语言·c++
瓜子三百克1 小时前
Objective-C 路由表原理详解
开发语言·ios·objective-c
幽蓝计划2 小时前
HarmonyOS NEXT仓颉开发语言实战案例:外卖App
开发语言·harmonyos
伍哥的传说2 小时前
鸿蒙系统(HarmonyOS)应用开发之实现电子签名效果
开发语言·前端·华为·harmonyos·鸿蒙·鸿蒙系统
androidwork2 小时前
深入解析内存抖动:定位与修复实战(Kotlin版)
android·kotlin
梦天20152 小时前
android核心技术摘要
android