Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

kotlin - Can't get access to Views by DataBinding or Android Extensions

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>
question from:https://stackoverflow.com/questions/65863480/cant-get-access-to-views-by-databinding-or-android-extensions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...