代码之家  ›  专栏  ›  技术社区  ›  Frank

如何用Java在Android中生成Spinner?

  •  0
  • Frank  · 技术社区  · 4 年前

    我想从我的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);
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   Md. Asaduzzaman    4 年前

    更新如下代码以创建 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);