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="viewModel"
type="com.example.mybluetooth.MainActivity" />
<variable
name="onClick"
type="android.view.View.OnClickListener" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/sppBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="36dp"
android:layout_marginTop="28dp"
android:onClick="@{viewModel::clickView}"
android:text="SPP"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/sppBtn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="36dp"
android:layout_marginTop="28dp"
android:onClick="@{(v)->viewModel.clickView(v)}"
android:text="SPP"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/sppBtn" />
<Button
android:id="@+id/sppBtn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="36dp"
android:layout_marginTop="28dp"
android:onClick="@{onClick}"
android:text="SPP"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/sppBtn2" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
String TAG = MainActivity.class.getSimpleName();
ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setViewModel(this);//将xml中定义的变量 viewModel赋值
binding.setOnClick(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.e(TAG,"setOnClickListener------"+view.getId());
}
});
Log.e(TAG, "OnCreate");
}
public void clickView(View view) {
Log.e(TAG,"clickView------"+view.getId());
int id = view.getId();
...
}
}
三种验证可行的click方式
网友评论