Hi All, I'm trying to change the background of 2 l...
# getting-started
k
Hi All, I'm trying to change the background of 2 layouts by using onClick. let's say there is Layout A and Layout B, the default form is that Layout A is active and Layout B is inactive, when the user click the button, Layout A become inactive and Layout B become active. active layout will use vector assets as background, while inactive layout will use simple color code(hexcode). to do that i was thinking this can be done by a simple ifelse function, did i do it right with this? or there is a better way to do this?
Copy code
var isColorChanged: Boolean? = true;

fun changeScreenClick(view: View) {
        if(isColorChanged==true){
            view_menu_1.resources.getColor(R.color.Yellow)
        }
        else{
            view_menu_2.resources.getDrawable(R.drawable.background_box)
        }
    }
Thank you!
s
Hey Kevin, I would suggest you have a selector background defined with two states, for example, enabled state true and false. Set this background for both of the views. and just toggle isEnable for both of views.
k
so, the selector background as statement inside the if else right?
s
You can go through this link to learn how to define a selector https://developer.android.com/guide/topics/resources/drawable-resource#StateList
Basically selector drawables are drawable xml which have items for one or many states. You assign them to a view mostly through xml
android:background="@drawable/selector"
. And then you can toggle state of the view like this
view.isEnabled = true/false
Based on the state the view currently is in, the correct background will be applied to the view.