M
M
Maxim Siomin2021-07-07 21:01:55
Android
Maxim Siomin, 2021-07-07 21:01:55

Why is data binding not working correctly?

All code is as short as possible
fragment_search.xml

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

    <data>
        <variable
            name="viewModel"
            type="com.example.domains.ui.mainActivity.searchFragment.SearchFragmentViewModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="ui.mainActivity.searchFragment.SearchFragment">
        <TextView
            android:id="@+id/domain_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/main_activity_start_end_margin_and_padding_for_text_views"
            android:layout_marginEnd="@dimen/main_activity_start_end_margin_and_padding_for_text_views"
            android:fontFamily="@font/roboto"
            android:text="@{viewModel.domainTextLiveData}"
            android:textSize="28dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/text_above_domain"
            tools:ignore="SpUsage"
            tools:text=".com"
            tools:visibility="visible" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

SearchFragment.kt
class SearchFragment : Fragment(R.layout.fragment_search) {
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        private var _binding: FragmentSearchBinding? = null
        // This property is only valid between onCreateView and onDestroyView
        private val binding get() = _binding!!
        mainActivity = activity as MainActivity
        activityContext = mainActivity.application
        viewModel =
            ViewModelProvider(this, SearchFragmentViewModelFactory(activityContext))
                .get(SearchFragmentViewModel::class.java)
        binding.viewModel = viewModel
    }
}

LivaData is updated, observers are working, but the text on the screen is empty

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Siomin, 2021-07-08
@MaxSiominDev

I should have added binding.lifecycleOwner = viewLifecycleOwnerthis code

P
Pavel, 2021-07-08
@LukyanovPA

So you didn't inflate the binding, you have it null.
https://developer.android.com/topic/libraries/data...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question