androidxmlandroid-layoutandroid-fragmentsfindviewbyid

findViewById Attribute in Fragment from the activity xml Not work


How to access an attribute in the activity xml? I want to use it in fragment.

for example : this is my activity xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:fab="http://schemas.android.com/apk/res-auto">

<androidx.constraintlayout.widget.ConstraintLayout
    fab:layout_constraintTop_toTopOf="parent"
    fab:layout_constraintLeft_toLeftOf="parent"
    fab:layout_constraintRight_toRightOf="parent"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/layTitle"
    android:layoutDirection="rtl"
    android:background="@color/colorPrimary"
    android:padding="@dimen/paddingTitle"
    android:elevation="@dimen/elevationActivityTitle"
    android:layout_alignParentTop="true">
    <ImageView
        fab:layout_constraintLeft_toLeftOf="parent"
        fab:layout_constraintTop_toTopOf="parent"
        fab:layout_constraintBottom_toBottomOf="parent"
        android:layout_width="@dimen/imgActivityTitle"
        android:layout_height="@dimen/imgActivityTitle"
        android:id="@+id/btn_back"
        android:src="@drawable/ic_back"
        android:elevation="5dp"
        android:layout_alignParentEnd="true"
        android:layout_centerVertical="true"/>
    

</androidx.constraintlayout.widget.ConstraintLayout>
<FrameLayout
    android:id="@+id/frag"
    android:layout_width="0dp"
    android:layout_height="0dp"
    fab:layout_constraintBottom_toBottomOf="parent"
    fab:layout_constraintTop_toBottomOf="@+id/layTitle"
    fab:layout_constraintLeft_toLeftOf="parent"
    fab:layout_constraintRight_toRightOf="parent"
    />
</androidx.constraintlayout.widget.ConstraintLayout>

I want findViewByid ImageView in fragment When I was searching for solution I got the following one:

TextView btn_back= (TextView) getView().findViewById(R.id.btn_back)

But, unfortunately it was not working for me.


Solution

  • You can use the interface to do it :

    Create an interface names IBtnClick with one void method: "void onBtnClicked();"

    use interface in activity like this:

    IBtnClick iBtnClick= (IBtnClick)getActivity();
    

    here getAtivity is our context, if it doesn't work use another scope context.

    and use your method in button click listener like this

    iBtnClick.onBtnClicked();
    

    Now in your fragment you have to implements interface and

    you can add any action you want in Overrided method.