我在constraintLayout中有一个按钮;(new onClickListener((("显示灰色,按钮不工作
findViewById (R.id.button_test).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "text", Toast.LENGTH_SHORT).show();
}
});
}
这是xml代码
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RecipeListActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button_test"
android:text="test"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
首先声明您的按钮,然后设置OnClickListener
,如下所示:
yourButton = findViewById (R.id.button_test);
yourButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "text", Toast.LENGTH_SHORT).show();
}
});
编辑:
在Java8中,引入了lambda表达式。这替换了许多冗余调用,比如在实现setOnClickListener
时。你看到的灰色表明可以通过以下操作简化该方法:
单击灰色区域,然后按alt
+Enter
将OnClickListener
转换为lambda表达式:
yourButton.setOnClickListener(v -> Toast.makeText(getApplicationContext(), "text", Toast.LENGTH_SHORT).show(); )