gpt4 book ai didi

java - Android Java - 下拉微调器始终设置相同的文本,只想更改背景颜色

转载 作者:行者123 更新时间:2023-12-01 09:13:48 24 4
gpt4 key购买 nike

我有 2 个下拉微调器,我想对其进行颜色编码。我希望 1 始终被标记为 Apple,而另一个始终被标记为 Banana。我正在使用下拉菜单来更改微调器的背景颜色。如何将文本设置为始终保持 Apple 和 Banana 状态,但仅根据所选内容更改微调器的背景颜色?每当我使用下拉菜单选择颜色时,它会将文本更改为我选择的颜色。我觉得我需要一个 setText 函数......

这是迄今为止我的代码:

    @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

dropdown1 = (Spinner)findViewById(R.id.spinner1);
dropdown2 = (Spinner)findViewById(R.id.spinner2);

String[] colors = new String []{"red", "blue", "green"};

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, colors);

dropdown1.setAdapter(adapter);
dropdown2.setAdapter(adapter);

dropdown1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
text1 = dropdown1.getSelectedItem().toString();

if (text1.equals("red")) {
dropdown1.setBackgroundColor(Color.parseColor("#ff0000"));
} else if (text1.equals("green")) {
dropdown1.setBackgroundColor(Color.parseColor("#00ff00"));
} else if (text1.equals("blue")) {
dropdown1.setBackgroundColor(Color.parseColor("#0000ff"));
}
}

@Override
public void onNothingSelected(AdapterView<?> parentView) {

}

});

最佳答案

添加以下代码,

dropdown1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
text1 = dropdown1.getSelectedItem().toString();

if (text1.equals("red")) {
dropdown1.setBackgroundColor(Color.parseColor("#ff0000"));
adapter.notifyDataSetChanged();
} else if (text1.equals("green")) {
dropdown1.setBackgroundColor(Color.parseColor("#00ff00"));
adapter.notifyDataSetChanged();
} else if (text1.equals("blue")) {
dropdown1.setBackgroundColor(Color.parseColor("#0000ff"));
adapter.notifyDataSetChanged();
}
}

@Override
public void onNothingSelected(AdapterView<?> parentView) {

}

});

关于java - Android Java - 下拉微调器始终设置相同的文本,只想更改背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40733801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com