Alia
Alia

Reputation: 13

Android: How to organize several screens with a bit different info?

I have several user roles in my app. Some screens for them should be almost similar except some small changes. Is there any way to create one layout for all users and then change some UI elements at runtime (after user logging) or should I create new layout for each user role? What is the best way?

Upvotes: 1

Views: 171

Answers (1)

323go
323go

Reputation: 14274

If the changes are truly minor, simply use the same layout for all, and then, based on the user-role, hide or remove UI elements not needed in the onCreate() call, for example:

public enum Roles { USER, ADMIN, SUPER };

private Roles myRole = Roles.USER;

@Override
protected void onCreate( Bundle data ) {
    super.onCreate( data );
    setContentView( R.layout.this_activity );
    myRole = getUserRole(); // This could inspect the Bundle or a singleton
    switch( myRole ) {
    case Roles.USER:
        findViewById( R.id.control1 ).setVisibility( View.GONE ); // This hides a control and the hidden control won't take up any space.
        findViewById( R.id.control2 ).setVisibility( View.INVISIBLE ); // This hides a control but leaves an empty space on the screen.
        findViewById( R.id.control3 ).setVisibility( View.VISIBILE );
        break;
    case Roles.ADMIN:
        findViewById( R.id.control4 ).setVisibility( View.GONE );
        findViewById( R.id.control5 ).setVisibility( View.INVISIBLE );
        findViewById( R.id.control6 ).setVisibility( View.VISIBILE );
        break;
    }
}

Note that you can make whole Layouts disappear with the above technique, so if you had a handful of super-admin buttons, place them in a LinearLayout, give the layout an id, and simply hide the entire bit with the technique above.

If the changes are a bit more substantial, you might want to look into using Fragments to tie together associated widgets, and then just add the Fragments to the layout which apply to the user role.

Generally, I would advise against using multiple Activities with nearly identical contents.

Upvotes: 1

Related Questions