Create a spinner programmatically in Android

后端 未结 2 634
我寻月下人不归
我寻月下人不归 2020-12-29 05:42

I want to create a spinner without using XML. I am new in android and my knowledge is limited. By now I have this code (see above) and I want my spinner in one of the tabs o

相关标签:
2条回答
  • 2020-12-29 06:01
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            LinearLayout layout = new LinearLayout(this);
    
            // The following can also be done using a loop
            ArrayList<String> spinnerArray = new ArrayList<String>();
            spinnerArray.add("one");
            spinnerArray.add("two");
            spinnerArray.add("three");
            spinnerArray.add("four");
            spinnerArray.add("five");
    
    
            Spinner spinner = new Spinner(MainActivity.this);
            ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, spinnerArray);
            spinner.setAdapter(spinnerArrayAdapter);
            layout.addView(spinner);
            setContentView(layout);
        }
        }
    
    0 讨论(0)
  • 2020-12-29 06:07

    You need to add the Spinner to a layout.

    First create a container for the Spinner and then create the Spinner and add it to your container. Next set content of you Activity to your container.

    This could be done like this, in your onCreate method:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
    
        LinearLayout layout = new LinearLayout(this);
    
        ArrayList<String> spinnerArray = new ArrayList<String>();
        spinnerArray.add("one");
        spinnerArray.add("two");
        spinnerArray.add("three");
        spinnerArray.add("four");
        spinnerArray.add("five");
    
        Spinner spinner = new Spinner(this);
        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, spinnerArray);
        spinner.setAdapter(spinnerArrayAdapter);
    
        layout.addView(spinner);
    
        setContentView(layout);
    }
    

    EDIT:

    Just to clarify: if the Spinner isn't added to the content of the Activity inside a layout, it isn't visible, so that's why you don't get any errors or anything, because there isn't any errors in your code, per se ;-)

    0 讨论(0)
提交回复
热议问题