Tries to add actions to the onClick()
event button (with DataBinding). I do everything like in the materials found on the web, but it doesn't work. The onSetLocationClick()
method is not called.
activity_main.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="location"
type="com.example.mytracker.model.Location" />
<variable
name="activity"
type="com.example.mytracker.MainActivity" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp"
tools:context=".MainActivity">
<TextView
android:id="@ id/tvLongitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:text='@{location.longitudeText}'
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@ id/bSetLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:onClick="@{() -> activity.onSetLocationClick()}"
android:text="SET LOCATION"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@id/tvLongitude" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
Location location = new Location();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setLocation(location);
TextView tvLabel = binding.tvLabel;
location.longitude = 1.1;
}
public void onSetLocationClick() {
location.longitude=99;
}
}
In build.gradle file i was added:
buildFeatures {
dataBinding true
}
I found a few similar threads but found no solution in any of them.
I will add that after changing the declaration
android:onClick="@{() -> activity.onSetLocationClick()}"
to
android:onClick="onSetLocationClick"
and declaration method from
public void onSetLocationClick()
to
public void onSetLocationClick(View view)
the code works fine.
However, I would like to use:
android:onClick="@{() -> activity.onSetLocationClick()}"
CodePudding user response:
You have to call setActivity()
on your binding to actually initialize your activity variable.
CodePudding user response:
setContentView(R.layout.activity_main);
Remove this line in your code and check it,