user1918418
user1918418

Reputation: 3

Adding fields dynamically to a layout in Android

In my application, I want to add fields dynamically based on the selection. While there are 4 fixed spinner fields, the values of spinner are dependent on the selection of the first spinner field etc. The second spinner field has to be populated based on the first field and the third spinner field based on the second field and so on.

Based on the options selected in these 4 spinner fields, the layout will contain additional fields that are text fields or radio buttons etc.

Can someone suggest what is the best way to achieve this or refer to other examples for this?

Thanks

Upvotes: 0

Views: 1601

Answers (1)

biddulph.r
biddulph.r

Reputation: 5266

You can add a View to a Layout similar to the below code:

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
            (LayoutParams.WRAP_CONTENT), (LayoutParams.WRAP_CONTENT));

RelativeLayout relativeLayout = new RelativeLayout(mContext);
relativeLayout.setLayoutParams(layoutParams);

TextView view = new TextView(mContext);
view.setLayoutParams(layoutParams);

relativeLayout.addView(view);

And then you need to add it to an existing ViewLayout:

LinearLayout originalLayout = findViewById(R.id.mylayout);
originalLayout.addView(relativeLayout);

This idea can be expanded on to add custom Views etc to your screen.

Upvotes: 2

Related Questions