问题
I need to put multiple spinners into my activity. Number of them would be defined dynamically, it would be 2-7 items.
At the moment I have something like:
-- clip:
Spinner spinnerOne = (Spinner) findViewById(R.id.spinnerBrowse);
spinnerOne.setAdapter(new Adapter(Browse.this, R.layout.browse_spinner_rows, picsIds));
spinnerOne.setOnItemSelectedListener(this);
Spinner spinnerTwo = (Spinner) findViewById(R.id.spinnerBrowse);
spinnerTwo.setAdapter(new Adapter(Browse.this, R.layout.browse_spinner_rows, picsIds));
spinnerTwo.setOnItemSelectedListener(this);
-- clap.
Contents of these spinners is the same, they only vary by names. Is it somehow possible to iterate by these names, like putting names into array { "SpinnerOne", "SpinnerTwo", "SpinnerThree", ... } and just generate number of needed spinner items in a loop?
回答1:
Sure define a container on your layout and then add spinners dinamically
int numOfSpinners;
LinearLayout container = (LinearLayout)findViewById(R.id.container);
for(int i=0;i<numOfSpinners;i++)
{
Spinner spinner = new Spinner(this);
spinner.setAdapter(new Adapter(Browse.this, R.layout.browse_spinner_rows, getPicsIds(i)));
spinner.setOnItemSelectedListener(this);
container.addView(spinner);
}
where getPicsIds() fetches the right items for each iteration
来源:https://stackoverflow.com/questions/16307636/multiple-spinners-in-an-activity-can-it-be-refactored-to-make-it-generated-dyn