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)
相关推荐
Aczone281 天前
硬件(六)arm指令
开发语言·汇编·arm开发·嵌入式硬件·算法
YA3331 天前
java设计模式二、工厂
java·开发语言·设计模式
逐雨~1 天前
9.8C++作业
开发语言·c++
我爱挣钱我也要早睡!1 天前
Java 复习笔记
java·开发语言·笔记
Yang-Never1 天前
Kotlin协程 -> Job.join() 完整流程图与核心源码分析
android·开发语言·kotlin·android studio
XeonYu1 天前
Kotlin 协程之 突破 Flow 限制:Channel 与 Flow 的结合之道
kotlin·coroutine·channelflow·callbackflow·receiveasflow·consumeasflow
TomCode先生1 天前
c#动态树形表达式详解
开发语言·c#
高-老师1 天前
基于R语言的物种气候生态位动态量化与分布特征模拟
开发语言·r语言·物种气候
大翻哥哥1 天前
Python 2025:量化金融与智能交易的新纪元
开发语言·python·金融
weixin_437830941 天前
使用冰狐智能辅助实现图形列表自动点击:OCR与HID技术详解
开发语言·javascript·ocr