如何添加自定义Spinner?

时间:2017-05-24 05:35:11

标签: android android-layout android-spinner

我正在开发一个我必须实现微调器的项目。我的微调代码如下:

  ArrayAdapter stringArrayAdapter = new ArrayAdapter(this, 
  android.R.layout.simple_spinner_dropdown_item, CatagoryName);

        // create a spinner
        Spinner spinner = (Spinner) findViewById(R.id.spinner);
        // add adapter to spinner
        spinner.setAdapter(stringArrayAdapter);
        // create listener and add to spinner
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // put code which recognize a selected element
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

基本上,我想在

使用我的自定义微调器布局
   ArrayAdapter stringArrayAdapter = new ArrayAdapter(this, 
   android.R.layout.simple_spinner_dropdown_item, CatagoryName);

R.layout.simple_spinner_dropdown不是我想要的。如何用我的替换这个布局?

2 个答案:

答案 0 :(得分:0)

尝试这种方法:

    Spinner spinner = (Spinner) findViewById(R.id.spinner);
    String[] CatagoryName = {"A","B","C","D"};
    ArrayAdapter<CharSequence> langAdapter = new ArrayAdapter<CharSequence>(getActivity(), R.layout.your_layout, CatagoryName);
    langAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown);
    spinner.setAdapter(langAdapter);

答案 1 :(得分:0)

这对我有用,  首先在strings.xml中定义微调器项,在上面的值目录中

&#13;
&#13;
 
  <string-array name="spinner_array">
        <item>item1</item>
        <item>item2</item>
        <item>item3</item>
    </string-array>
&#13;
&#13;
&#13;

然后尝试上面的代码,

 Spinner customSpinner = (Spinner)findViewById(R.id.spinner);

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.spinner_array, R.layout.custom_spinner_dropdown);

    customSpinner.setAdapter(adapter);