ANDROID Adaptor inflating dynamic layout from its string name

554 Views Asked by At

I have on stacked card view. So each card is set tasks. For that each card may have different layouts.I want know how to inflate the different layout .

To do that i created on string array to hold my all layout name.

private ArrayList<String> LayOutData;
for (int x = 0; x < 4; x++) { 
   LayOutData.add("card_"+(x + 1));
}

This LayOutData i am passing to my adaptor like

mAdapter = new SwipeStackAdapter(mData,LayOutData);

my layout name are like

card_1.xml
card_2.xml
card_3.xml
card_4.xml

This is the static way setting the layout for the view.

convertView = getLayoutInflater().inflate(R.layout.card_1, parent, false);

But how can i inflate the names that i have created the already with the card index. My try for this is below.

switch (position){
                case 0:
                    convertView = getLayoutInflater().inflate(R.layout.card_1, parent, false);
                    break;
                case 1:
                    convertView = getLayoutInflater().inflate(R.layout.card_2, parent, false);
                    break;
                case 2:
                    convertView = getLayoutInflater().inflate(R.layout.card_3, parent, false);
                    break;
                case 3:
                    convertView = getLayoutInflater().inflate(R.layout.card_3, parent, false);
                    break;
                default:
                    convertView = getLayoutInflater().inflate(R.layout.card_1, parent, false);
                    break;
            }

I know this is not good way to code can you please suggest some way to this.

1

There are 1 best solutions below

4
On BEST ANSWER
int id = getContext().getResources().getIdentifier(cardName, "layout", packageName);
getLayoutInflater().inflate(id, parent, false);