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)
相关推荐
Nturmoils1 天前
基于Rokid CXR-M SDK实现智能眼镜实时翻译应用:从零到一的完整实践
android
APItesterCris1 天前
Node.js/Python 实战:编写一个淘宝商品数据采集器
大数据·开发语言·数据库·node.js
余辉zmh1 天前
【C++篇】:LogStorm——基于多设计模式下的同步&异步高性能日志库项目
开发语言·c++·设计模式
艾莉丝努力练剑1 天前
【C++STL :list类 (二) 】list vs vector:终极对决与迭代器深度解析 && 揭秘list迭代器的陷阱与精髓
linux·开发语言·数据结构·c++·list
我想吃辣条1 天前
flutter google play 应用不支持 16 KB
android·flutter
努力也学不会java1 天前
【Java并发】深入理解synchronized
java·开发语言·人工智能·juc
星竹晨L1 天前
【C++】深入理解list底层:list的模拟实现
开发语言·c++
宴西笔记1 天前
手机AIDE使用OpenCV
android
豐儀麟阁贵1 天前
Java知识点储备
java·开发语言
豐儀麟阁贵1 天前
2.3变量与常量
java·开发语言