How to access parent layout without id from child textview with id programatically in android fragment?

70 Views Asked by At

I am now trying to change the background color of the parent layout of the textview given the id inside the fragment. Is it possible to dynamically call the parent layout with the child textview and change the background color without giving the parent an id?

<androidx.appcompat.widget.LinearLayoutCompat
    android:layout_width="40dp"
    android:layout_height="30dp"
    android:layout_marginLeft="12dp"
    android:gravity="center"
    >
    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/actv_notify_all"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/gray_7f"
        android:textSize="13sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="진료" />

</androidx.appcompat.widget.LinearLayoutCompat>

This is xml code.

I thought maybe there is a .parent() function just like a jquery selector.

1

There are 1 best solutions below

0
rCr_BD On

This can be done by calling parents on child view and cast that view accordingly. In this case, your child view name is actv_notify_all and its parent is a LinearLayoutCompat without any ID.

val textView: TextView = view.findViewById(R.id.actv_notify_all)
(textView.parent as LinearLayoutCompat).setBackgroundColor(Color.BLUE)