gpt4 book ai didi

android - findViewById() 返回从数据绑定(bind)创建的空 View

转载 作者:行者123 更新时间:2023-11-30 04:59:04 25 4
gpt4 key购买 nike

出于某种原因,当我使用 findFragmentById() 来引用使用数据绑定(bind)创建的 SeekBar View 时,它会返回一个空对象。请问如何获取此 View 的引用?

这是我的搜索栏:

<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<SeekBar
android:id="@+id/seekBar"
android:layout_width="match_parent"
android:layout_height="match_parent">
</SeekBar>
</layout>

这是我的课:

open class UtilClass(activity: Activity) {
...
val seekBar = activity.findViewById<SeekBar>(R.id.seekBar)
..
}

seekbar 在它自己的 Fragment 中使用 DataBindingUtil 膨胀:

class SeekBarFragment(): Fragment {
...
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding: SeekbarBinding = DataBindingUtil.inflate(inflater, R.layout.seekbar, container, false)
...
}

UtilClass 在这里被实例化:

class MainActivity : AppCompatActivity() {

private lateinit var mUtilClass: UtilClass
....
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mUtilClass = UtilClass(requireActivity())
retainInstance = true

var fm = fragmentManager
var fragment: Fragment? = fm!!.findFragmentById(R.id.seek_container)

if (fragment == null) {

fragment = SeekBarFragment.newInstance()

fm.beginTransaction()
.add(R.id.seek_container, fragment)
.commit()
}
}

绑定(bind)在这里创建:

class SeekBarFragment: Fragment() {

companion object {
fun newInstance(): SeekBarFragment {
return SeekBarFragment()
}
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
super.onCreate(savedInstanceState)
}

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding: SeekbarBinding = DataBindingUtil.inflate(inflater, R.layout.seekbar, container, false)
...
}

最佳答案

您应该指定父布局 View 。

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

var v: View =inflater.inflate(R.layout.seekbar, container, false)
var seekbar=v.findViewById(R.id.seekbar)

return v

}

关于android - findViewById() 返回从数据绑定(bind)创建的空 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58561365/

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