【发布时间】:2021-07-07 03:45:21
【问题描述】:
如何在单击按钮时更改按钮的颜色,我正在制作一个测验应用程序,当单击按钮时它会更改其颜色
【问题讨论】:
标签: java android button android-button material-components-android
如何在单击按钮时更改按钮的颜色,我正在制作一个测验应用程序,当单击按钮时它会更改其颜色
【问题讨论】:
标签: java android button android-button material-components-android
您可以使用MaterialButtonToggleGroup 从一组选项中进行选择:
<com.google.android.material.button.MaterialButtonToggleGroup
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:singleSelection="true"
app:selectionRequired="true">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1"
style="?attr/materialButtonOutlinedStyle"
/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2"
style="?attr/materialButtonOutlinedStyle"
/>
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 3"
style="?attr/materialButtonOutlinedStyle"
/>
</com.google.android.material.button.MaterialButtonToggleGroup>
【讨论】:
只需将View.OnClickListener 设置为您的按钮并将setBackgroundColor 设置为它。
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.setBackgroundColor(Color.parseColor("#ff0000"));
}
});
如果你想在点击另一个按钮时重置颜色,你可以在按钮之间使用一个通用的OnClickListener。下面是一个例子:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button button1;
private Button button2;
private Button button3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = findViewById(R.id.button1);
button2 = findViewById(R.id.button2);
button3 = findViewById(R.id.button3);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
button1.setBackgroundColor(Color.parseColor("#ff0000"));
button2.setBackgroundColor(Color.parseColor("#0000ff"));
button3.setBackgroundColor(Color.parseColor("#0000ff"));
break;
case R.id.button2:
button1.setBackgroundColor(Color.parseColor("#0000ff"));
button2.setBackgroundColor(Color.parseColor("#ff0000"));
button3.setBackgroundColor(Color.parseColor("#0000ff"));
break;
case R.id.button3:
button1.setBackgroundColor(Color.parseColor("#0000ff"));
button2.setBackgroundColor(Color.parseColor("#0000ff"));
button3.setBackgroundColor(Color.parseColor("#ff0000"));
break;
}
}
}
【讨论】: