For some reason when I use findFragmentById() to reference a SeekBar view created with a databinding it returns a null object. How can I get a reference for this view, please?
This is my seekBar:
<?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>
This is my class:
open class UtilClass(activity: Activity) {
...
val seekBar = activity.findViewById<SeekBar>(R.id.seekBar)
..
}
The seekbar is inflated using DataBindingUtil in its own Fragment:
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 is instantiated here:
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()
}
}
Binding is created here:
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)
...
}
You should specify the parent layout 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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.