如何使用 Java 在 Android 中生成 Spinner?

How To Generate A Spinner in Android With Java?

我想从我的 Java 代码向我的 android 应用程序添加一个微调器,而不需要触摸 xml 文件,所以我进行了一些搜索并找到了一些代码做了一些,但它仍然使用 "findViewById" 从 xml 获取微调器,我将其替换为: 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 文件

//Create spinner dynamically
Spinner spinner = new Spinner(context);

//Ready your data for spinner
String[] plants = new String[]{"Laceflower", "California sycamore", 
        "Mountain mahogany", "Butterfly weed", "Carrot weed"};

//Create ArrayAdapter for spinner with system default layout for views
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
        this, 
        android.R.layout.simple_spinner_item, 
        plants
);

//Attach adapter to spinner
spinner.setAdapter(spinnerArrayAdapter);