user2455235
user2455235

Reputation:

Android - Dynamically name resources inside code

Quiet simply, I am trying to reuse my Adapters and Activity classes. When I call the Intent to open my Activity, I pass name of the Layout I want to inflate as a StringExtra like this:

i.putExtra("layout_name", "layout_a");

Then inside my Activity I obtain the extra:

Intent i = getIntent();
String layout_name = i.getStringExtra("layout_name");

Now I want to use this in this format:

setContentView(R.layout. + layout_name); 

Is something like this possible? What's the correct syntax?

Upvotes: 1

Views: 84

Answers (3)

user370305
user370305

Reputation: 109237

Something like,

int layoutID = getResources().getIdentifier("layout_name" , "layout", getPackageName());
setContentView(layoutID); 

Upvotes: 4

Shamim Ahmmed
Shamim Ahmmed

Reputation: 8383

You could pass layout identifier:

i.putExtra("layout_id", R.layout.your_layout);

Get this value as

int layout_id = getIntent().getIntExtra("layout_id");

Set this id as

setContentView(layout_id); 

Upvotes: 1

Armaan Stranger
Armaan Stranger

Reputation: 3130

You can also try Int ID of resource and use it.

int layout = getIntent().getExtras().getInt("LayoutID");
setContentView(layout);

Hope it Helps!!

Upvotes: 1

Related Questions