gpt4 book ai didi

android - 无法通过 DataBinding 或 Android 扩展访问 View

转载 作者:行者123 更新时间:2023-12-05 00:15:37 24 4
gpt4 key购买 nike

我无法通过 DataBinding 或 Android Extensions 更改 Views 的值,但它可以通过“传统方式”(findViewById)工作。此外,当我在没有安全调用运算符(operator)的情况下通过 Android Extensions 的方式尝试时,它会抛出 NPE。
HourlyFragment.kt

class HourlyFragment : Fragment() {

private lateinit var binding: FragmentHourlyBinding

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {

var rootView = inflater.inflate(R.layout.fragment_hourly, container, false)

binding = DataBindingUtil.inflate(
inflater, R.layout.fragment_hourly, container, false
)

// doesn't work
//binding.tvHourly.text = "HOURLY!"

val tvHourly : TextView = rootView.findViewById(R.id.tv_hourly)
tvHourly.setText("HOURLY!!")

// doesn't work, without safe call operator throws NullPointerException
//tv_hourly?.text = "HOURLY!!!"

return rootView
}
}
fragment_hourly.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.HourlyFragment">


<TextView
android:id="@+id/tv_hourly"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="hourly fragment" />

</FrameLayout>
</layout>

最佳答案

目前您正在夸大您的观点两次,这导致了我认为的所有问题,因此只需夸大您的观点一次,看看它是否能解决您的问题
尝试以下

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {

// var rootView = inflater.inflate(R.layout.fragment_hourly, container, false)

binding = DataBindingUtil.inflate(
inflater, R.layout.fragment_hourly, container, false
)

binding.tvHourly.text = "HOURLY!"

// val tvHourly : TextView = rootView.findViewById(R.id.tv_hourly)
tvHourly.setText("HOURLY!!")



return binding.root
}

关于android - 无法通过 DataBinding 或 Android 扩展访问 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65863480/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com