简体   繁体   中英

Android: different activity_main.xml depending on user's previleges

Right now I am trying to implement different main activity of the app depending on the role of the user that is stored at the server-side database. Upon login it is returned to device.

Here Single application with different UIs depending on the user's role there was a similar topic to what I would like to achieve, but it did not offer what I wanted to achieve.

What I do is loading the login activity in MainActivity's onCreate(). After that I check the role and depending on this I use:

if (some condition here){
    //here I set the activity_main.xml
} else if (condition again) {
    //another variant of activity_main.xml
}

Is this the correct variant to do this? If not, are there any other ways to achieve this? By the way, when I connect user interface elements to xml's values outside of the corresponding conditional block, I keep getting a NullPointerException later on, even if I use the login credentials for the most privileged user, whose interface has the maximum elements (names of views are the same in all xml layouts, files only differ in number of elements).

Sure thing, I know I will be advised to use the login screen as the main one of my app (like the link above suggested), but the app is not going to require login every time it is started, and thus I do not really understand how to realise all this stuff.

Any help is appreciated.

You can inflate different layouts based on the conditions in your onCreate(): setContentView(R.layout.your_layout); . Make sure not to initialize widgets that you are not using in the layout though, as that can cause errors.

More complete example:

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (condition1)
        setContentView(R.layout.your_layout1);
    else
        setContentView(R.layout.your_layout2);
}

I'd also recommend leaving an else condition in the event something goes wrong, so it loads a layout rather than crash your application.

My suggestion would be , Suppose you are having **activity_main.xml** and **activity_main_two.xml** as your 2 xml files each having different roles , check the the password and the username in the Login section to verify which kind of the user has logged in , then afterwards you make your logic.

Suppose you have two users in the company Managers and Employees

E,g like this pseudo code below:

if (user_is_an_executive){
 setContentView(R.layout.activity_main.xml);
}
else if (user_is_another_employee){
setContentView(R.layout.activity_main_two.xml );
}

NOTE:

Place this in the onCreate Method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM