java - 如何在Android中使用Java在每个项目中生成具有不同背景颜色的微调器?
问题描述
我想在 Java 中生成一个用于颜色选择的微调器,它在下拉时应该是这样的:
我的 Java 代码现在看起来像这样:
final Spinner spinner = new Spinner(context);
String[] colors = new String[]{"[1]", "[2]", "[3]", "[4]", "[5]", "[6]"};
final List<String> colorsList = new ArrayList<>(Arrays.asList(colors));
final ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, colorsList) {
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) super.getDropDownView(position, convertView, parent);
Color color = Color.rgb(18,18,218);
switch(position){
case 0:
color = Color.rgb(28,158,218);
break;
case 1:
color = Color.rgb(218,58,218);
break;
case 2:
color = Color.rgb(128,18,28);
break;
}
return view;
}
};
但现在没有显示颜色,全是白色。有什么更好的方法来做到这一点?
解决方案
而不是TextView
设置BackgroundColor
为view
. 除此之外,如果要为所选视图着色,则还必须覆盖getView
. 检查以下:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
private View getCustomView(int position, View convertView, ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
if (position % 2 == 1) {
view.setBackgroundColor(Color.parseColor("#FFC3C0AA"));
}
else {
view.setBackgroundColor(Color.parseColor("#FFB5DCE8"));
}
return view;
}
输出:
推荐阅读
- powerbi-desktop - 如何在 Power BI 的堆积条形图中删除总计
- botframework - Microsoft 框架 BOT 的消息传递端点
- javascript - 使用带时间轴的 ECharts visualMap
- reactjs - InputField onChange 显示错误“字段应该是可变的”
- c - 如何使用 Linux Netlink 套接字监视输入设备的添加和删除
- python - 错误处理不适用于 Python 中的 Selenium 异常
- flask - 尽管使用生产配置,Flask 应用程序仍处于开发模式?
- excel - 在 Excel VBA 问题中打开超链接
- swift - SwiftUI 在单个 ScrollView 中嵌套 LazyVStacks
- xcode - XCode Preview Canvas 不工作:文件不在源代码控制之下