我想从我的Java代码中添加一个spinner到我的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);