My question is simple but I can't seem to do what I want to.
So In my activity I have this method.
public void performButtonClick(View view)
{
Log.i("INTRO", "OK");
}
Which is called from a button click event defined in xml like so
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="performButtonClick"
android:text="@string/start"/>
Now I've heard that this approach is using reflection which slows down performance so I'm trying to replace the onClick
event with databinding.
I tried various combinations like
android:onClick="@{performButtonClick}"
or
android:onClick="@{(v) -> performButtonClick(v)}"
or
android:onClick="@{(v) -> MainActivity::performButtonClick}"
but None of these worked.
Could you help me out?
Ok answering to my own question.
I am new to DataBinding but I do not understand why I have to use copy-pasted solutions which make use of an accessory Handlers
class and end up with more boilerplate code than I used to have.
All I wanted is an equivalent to android:onClick="performButtonClick"
So here is my solution:
activity_main.xml
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="activity"
type="com.example.mydatabinding.MainActivity"/>
</data>
<LinearLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="@{activity::performButtonClick}"
android:text="@string/start"/>
</LinearLayout>
MainActivity.java
public final class MainActivity extends AppCompatActivity
{
ActivityMainBinding binding;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setActivity(this);
}
public void performButtonClick(View view)
{
Log.i("INTRO", "OK");
}
}