0

I'm trying to use Data binding to run a function when an onClick event occurs, I'm hoping someone can tell me what I'm doing wrong here.

The log item in myClick doesn't run.

XML

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="myBinding"
            type="com.example.deletebindingtest.MyFragment" />
    </data>

    <androidx.appcompat.widget.LinearLayoutCompat
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MyFragment"
        android:orientation="vertical">

        <Button
            android:id="@+id/my_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/button"
            android:onClick="@{(view) -> myBinding.myClick()}"/>

    </androidx.appcompat.widget.LinearLayoutCompat>
</layout>

My Fragment

class MyFragment : Fragment() {  
  private lateinit var binding: FragmentMyBinding

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

        // Inflate view and obtain an instance of the binding class
        binding = DataBindingUtil.inflate(
            inflater,
            R.layout.fragment_my,
            container,
            false
        )

        binding.lifecycleOwner = viewLifecycleOwner
        return binding.root
    }


    fun myClick() {
        Log.i("TEST", "Its working")
    }
}

When I click on the extension in the XML it takes me to myClick function.

Shawn
  • 1,222
  • 1
  • 18
  • 41

1 Answers1

1

a Quick fix is on onCreateView add binding.myBinding=this

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

    // Inflate view and obtain an instance of the binding class
    binding = DataBindingUtil.inflate(
        inflater,
        R.layout.fragment_my,
        container,
        false
    )

    binding.lifecycleOwner = viewLifecycleOwner
    binding.myBinding=this // here
    return binding.root
}

also I prefer listener binding you can check it here

Mohammed Alaa
  • 3,140
  • 2
  • 19
  • 21
  • This is great but it leaves me with more questions. Can you explain why I need "binding.myBinding = this " does? Is the current code not written as listener binding? – Shawn Jun 20 '20 at 18:30
  • you need this to assign a value to the binding variable in xml – Mohammed Alaa Jun 20 '20 at 18:35
  • I wouldn't mind reading more up on that but I can't seem to find a reference to it in the documentation. Do you know where I can find it? – Shawn Jun 20 '20 at 18:42
  • you can check [this link](https://stackoverflow.com/questions/37105066/android-data-binding-pass-arguments-to-onclick-method) I think it's a similar question , but with passing arguments – Mohammed Alaa Jun 20 '20 at 18:48