Multiple spinners in an activity - can it be refactored to make it generated dynamically?

北城余情 提交于 2019-12-24 06:44:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!