1

Let's say I have two layouts activity_home_1 and activity_home_2 for my HomeActivity. I want to be able to switch between them like I used to do in Java:

int layout = getResources().getIdentifier("activity_home_" + getHomeScreenNumber(),"layout",getPackageName());
setContentView(layout);

And later reference elements of my layout using findViewById();

Of course, all the elements in those two layouts are named the same, they are just different looking, so this is working perfectly in Java.


On the other side in Kotlin, I'm avoiding findViewById() and I'm using Kotlin Android Extensions, and it's working great with including one layout like this:

import kotlinx.android.synthetic.main.activity_home_1.*

The trouble is when I want to switch between them. Just simply adding another import for the other layout it's causing an error because it doesn't know which layout to look at (cause they both have the same fields).

How can I switch between two layouts when using Kotlin Android Extensions?

1
  • 2
    You should consider using fragments in this case. Anyhow you won't be able to achieve this in the Activity. If all views are the same by type, you wouldn't even need to. The synthetic properties don't verify your layout. Also you have to consider the caching of the views with the synthetic properties. So you'd have to disable caching or make sure the cache is cleared. Commented Jan 23, 2019 at 9:39

1 Answer 1

1

The answer was simple and I wasn't paying enough attention. It was to include the desired layout with:

setContentView(..)

For example, if you include

  • import kotlinx.android.synthetic.main.activity_home_1.*

and in your OnCreate() set the

  • setContentView(R.layout.activity_home_3)

Now, your activity_home_3 layout will be shown and their elements will be referenced!

No need for findViewById()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.