0

I have a custom toolbar view in my app. Using custom attributes, i defined custom states for this toolbar (enum with values HOME=0, SUBPAGE=1).

In this toolbar i have a selector drawable custom_nav_icon.xml which has different drawables based on state.

I want the drawable to update based on the state of my custom toolbar (home/sub-page). Is this possible? I tried using android:duplicateParentState="true" but that doesn't seem to work.

Code for reference.

res/layout/custom_toolbar_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:actionBarSize"
>
    <ImageView
        android:id="@+id/nav_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        **android:duplicateParentState="true"**
        android:layout_alignParentStart="true"
        **android:src="@drawable/custom_nav_icon"**/>
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/search_icon"
        android:layout_alignParentEnd="true"
        android:src="@drawable/ic_search"/>

Custom attributes (res/values/attrs.xml) -

    <declare-styleable name="MyCustomToolbar">
    <attr name="state" format="enum">
        <enum name="home" value="0"/>
        <enum name="subpage" value="1"/>
    </attr>
</declare-styleable>

res/layout/activity_main.xml -

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

**<com.sample.MyCustomToolbar
    android:id="@+id/myToolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:state="subpage"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    />**
<FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="?android:actionBarSize"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/myToolbar">

</FrameLayout>

res/drawable/custom_nav_icon.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:drawable="@drawable/ic_home" **app:state="home"** />
    <item android:drawable="@drawable/ic_back" **app:state="subpage"**/>
</selector>

Thanks!

user1122549
  • 664
  • 1
  • 13
  • 27

0 Answers0