It’s been a while since I last shared a tech post. Almost every week—or sometimes even daily—I update my Android portfolio app, Power Budget Tracker, by adding new features and refining the code. Recently, I introduced a feature that allows the app to switch between two different layouts based on the logged-in user. This functionality was inspired by a similar requirement I encountered at work, where I implemented a comparable solution.
Drawing from that professional experience, I incorporated this feature into my portfolio app. Below is a sample of the code used to achieve it:
View rootView;
boolean isAdmin = checkIfUserIsAdmin();
if (isAdmin) {
rootView = inflater.inflate(R.layout.layout_admin_dashboard, container, false);
// Admin-specific views
cardView1 = (CardView) rootView.findViewById(R.id.admin_card_1);
if (cardView1 != null) {
cardView1.setOnClickListener(this);
}
cardView2 = (CardView) rootView.findViewById(R.id.admin_card_2);
if (cardView2 != null) {
cardView2.setOnClickListener(this);
}
cardView3 = (CardView) rootView.findViewById(R.id.admin_card_3);
if (cardView3 != null) {
cardView3.setOnClickListener(this);
}
} else {
rootView = inflater.inflate(R.layout.layout_user_dashboard, container, false);
// User-specific views
userCard1 = (CardView) rootView.findViewById(R.id.user_card_1);
if (userCard1 != null) {
userCard1.setOnClickListener(this);
}
userCard2 = (CardView) rootView.findViewById(R.id.user_card_2);
if (userCard2 != null) {
userCard2.setOnClickListener(this);
}
userCard3 = (CardView) rootView.findViewById(R.id.user_card_3);
if (userCard3 != null) {
userCard3.setOnClickListener(this);
}
}
return rootView;
This is the default User layout.
This is the admin layout.