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)
相关推荐
楼田莉子2 分钟前
高并发内存池项目:内存池性能分析及其优化
开发语言·c++·后端·学习
是翔仔呐9 分钟前
第6章 UART串口通信!掌握单片机与外界的双向数据通道,实现跨设备交互
c语言·开发语言·单片机·嵌入式硬件·gitee
带娃的IT创业者10 分钟前
从本地开发到 PyPI发布:WeClaw 的 Python 包标准化之旅
开发语言·python
2201_7586426411 分钟前
自定义内存检测工具
开发语言·c++·算法
吠品14 分钟前
QEMU Windows虚拟机NAT网络配置指南:实现IP自动获取与外部访问
开发语言·php
fpcc15 分钟前
C++编程实践—操作系统调优和内核旁支
开发语言·c++
不想看见40421 分钟前
QAbstractItemModel 自定义实现--Qt 模型 / 视图(MVC)
开发语言·qt·mvc
不想看见40422 分钟前
Qt 事件循环与事件过滤器讲解【详细】
开发语言·数据库·qt
FL162386312923 分钟前
基于yolov8+pyqt5实现的水尺图像识别与水深计算系统
开发语言·qt·yolo
sycmancia23 分钟前
QT——GUI程序原理分析、Hello QT、调试的基本方法
开发语言·qt