I can't change value of Views by DataBinding or by Android Extensions, but it works by 'traditional way' (findViewById). Also, it throws NPE when I try by Android Extensions' way without safe call operator.
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>
Currently you are inflating your views twice and that's causing all the issues I believe, so instead just inflate your views once and see if it solves your issue
Try the following
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
}