Search code examples
androidandroid-layoutandroid-relativelayout

Change border colour of Relative Layout with respect to the focus of inner edit text in Android


I have a Relative layout and a few inner views within it. I have to change the border color of the relative layout with respect to the focus of an inner edit text.

here is layout code:

  <RelativeLayout
        android:id="@+id/outer_layout"
        android:layout_width="@dimen/layout_width"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/margin_top"
        android:background="@drawable/text_box">

        <EditText
            android:id="@+id/my_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            android:fontFamily="sans-serif"
            android:hint="@string/password"
            android:imeActionId="2"
            android:inputType="textPassword"
            android:nextFocusDown="@+id/login"
            android:padding="@dimen/ield_padding"
            tools:ignore="Autofill"/>

        <FrameLayout
           <----other layouts goes here--->
        </FrameLayout>


    </RelativeLayout>

here is my text_box drawable:

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:state_focused="true">
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
        <solid android:color="#ffffffff"/>
        <corners android:radius="1px"/>
        <stroke android:width="1.5dp" android:color="#ffffff"/> <!--outline stroke -->
        <padding android:left="0dp" android:top="0dp" android:right="0dp" android:bottom="0dp" />
    </shape>
</item>
<item >
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
        <solid android:color="#ffffffff"/> 
        <corners android:radius="10px"/>
        <stroke android:width="1dp" android:color="#000000"/> <!--outline stroke -->
        <padding android:left="0dp" android:top="0dp" android:right="0dp" android:bottom="0dp" />
    </shape>
</item>

How to change the border color of outer_laoyout on focusing the inner edit text my_password?


Solution

  • Set the relative layout background based on the edit text focus value got in onFocus change listener.

    override fun onFocusChange(view: View?, hasFocus: Boolean) {
        val background: Int = if (hasFocus) {
            R.drawable.background_focused
        } else {
            R.drawable.normal_background
        }
        setLayoutBackground(background)
    }
    

    Post if you have any better solution.