我想从Java代码中将微调器添加到我的android应用程序中,而无需触摸xml文件,因此我进行了一些搜索,找到了一些可以做到这一点的代码,但是它仍然使用“ findViewById”来获取来自xml的spinner,我将其替换为:Spinner spinner = new Spinner(context);
但在代码中它具有“ R.layout.spinner_item”,在我的情况下,该如何绕过?代码看起来像这样:
final Spinner spinner = new Spinner(context);
String[] plants = new String[]{"Laceflower", "California sycamore", "Mountain mahogany", "Butterfly weed", "Carrot weed"};
final List<String> plantsList = new ArrayList<>(Arrays.asList(plants));
final ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, R.layout.spinner_item, plantsList) <--- ?
{
@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);
if (position % 2 == 1)
{
tv.setTextColor(Color.parseColor("#FF7C7967"));
tv.setBackgroundColor(Color.parseColor("#FFC3C0AA"));
}
else
{
tv.setTextColor(Color.parseColor("#FF657A86"));
tv.setBackgroundColor(Color.parseColor("#FFB5DCE8"));
}
return view;
}
};
spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item); <--- ?
spinner.setAdapter(spinnerArrayAdapter);
如下更新代码以在运行时创建Spinner
而没有layout
文件
final Spinner spinner = new Spinner(context);
String[] plants = new String[]{"Laceflower", "California sycamore", "Mountain mahogany", "Butterfly weed", "Carrot weed"};
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, plants);
spinner.setAdapter(spinnerArrayAdapter);