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)
相关推荐
Dreamsi_zh10 分钟前
Python爬虫07_Requests爬取图片
开发语言·爬虫·python
梦想改变生活27 分钟前
《Flutter篇第二章》MasonryGridView瀑布流列表
android·flutter
蒋星熠30 分钟前
字母异位词分组(每天刷力扣hot100系列)
开发语言·c++·算法·leetcode·职场和发展
杨航 AI40 分钟前
PHP 5.5 Action Management with Parameters (English Version)
android·开发语言·php
代码的余温1 小时前
Java试题-选择题(2)
java·开发语言
lemon_sjdk1 小时前
java笔记——ConcurrentLinkedQueue
java·开发语言·笔记
封奚泽优1 小时前
使用Python制造扫雷游戏
开发语言·python·游戏·pygame·扫雷·random
超浪的晨1 小时前
Maven 与单元测试:JavaWeb 项目质量保障的基石
java·开发语言·学习·单元测试·maven·个人开发
魂尾ac1 小时前
因为想开发新项目了~~要给老Python项目整个虚拟环境
开发语言·python
不会理财的程序员不是好老板2 小时前
Java Spring Boot项目中集成Swagger完整步骤
java·开发语言·spring boot