【发布时间】:2025-12-06 06:20:06
【问题描述】:
我必须创建一个包含一些颜色的微调器,当您选择其中一种颜色时,按钮的背景颜色会发生变化。 这是我尝试过的:
<resources>
<string name="app_name">MyFirst</string>
<string-array name="colors_array">
<item>red</item>
<item>green</item>
<item>blue</item>
<item>pink</item>
</string-array>
</resources>
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.colors_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
bClick.setBackgroundColor( getResources().getColor(R.color.red));
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
bClick.setBackgroundColor( getResources().getColor(R.color.blue));
}
});
现在它使我的按钮变为红色,但我不知道如何将其更改为所选颜色,如何按名称(作为字符串)获取颜色值。这是我的 colors.xml
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<color name="red">#FF0000</color>
<color name="green">#00FF00</color>
<color name="blue">#0000FF</color>
<color name="pink">#FF4081</color>
</resources>
【问题讨论】: