[android] get parent's view from a layout

I have a FragmentActivity with this layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/menulabel"
    android:textSize="24sp" />

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="text"
    android:layout_below="@+id/textView1"
    android:hint="@string/search_title_hint" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/spinnersearch"
    android:layout_below="@+id/editText1" />

<LinearLayout
    android:id="@+id/layout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView2" >

    <Spinner
        android:id="@+id/spinner_search"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:prompt="@string/spinnersearch" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/reset_search" />

</LinearLayout>

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/buttonnewcat"
    android:layout_below="@+id/layout1" />

<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/buttondelcat" 
    android:layout_below="@+id/button2" />

<Button
    android:id="@+id/button4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/buttoneditcat"
    android:layout_below="@+id/button3" />

<Button
    android:id="@+id/button5"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/buttonnewtext"
    android:layout_below="@+id/button4" />

<Button
    android:id="@+id/button6"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/buttondeltext"
    android:layout_below="@+id/button5" />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <side.menu.scroll.ScrollerLinearLayout
        android:id="@+id/menu_content_side_slide_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:background="@drawable/ab_solid_example"
            android:orientation="horizontal" >

            <ImageView
                android:id="@+id/main_tmp_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/actionbar_background"
                android:src="@drawable/download" />

        </LinearLayout>
        <FrameLayout
            android:id="@+id/fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/bg_groud" />

    </side.menu.scroll.ScrollerLinearLayout>
</RelativeLayout>

and the ScrollerLinearLayout class is something like this:

public class ScrollerLinearLayout extends LinearLayout {
    // code of the class
}

How to access from ScrollerLinearLayout to the parent layout to get - for example - the editetxt? FragmentActivity and ScrollerLineraLayout are in different packages of the same projects. I tried to use the getParent() function in this way within the ScrollerLinearLayout but it doesn't work.

RelativeLayout r = (RelativeLayout) this.getParent().getParent();
int w = r.findViewById(R.id.editText1).getLayoutParams().width;

Someone help me? Thanks!

This question is related to android android-layout view parent-child

The answer is


If you are trying to find a View from your Fragment then try doing it like this:

int w = ((EditText)getActivity().findViewById(R.id.editText1)).getLayoutParams().width;

You can get ANY view by using the code below

view.rootView.findViewById(R.id.*name_of_the_view*)

EDIT: This works on Kotlin. In Java, you may need to do something like this=

this.getCurrentFocus().getRootView().findViewById(R.id.*name_of_the_view*);

I learned getCurrentFocus() function from: @JFreeman 's answer


The RelativeLayout (i.e. the ViewParent) should have a resource Id defined in the layout file (for example, android:id=@+id/myParentViewId). If you don't do that, the call to getId will return null. Look at this answer for more info.


Just write

this.getRootView();

Check my answer here

The use of Layout Inspector tool can be very convenient when you have a complex view or you are using a third party library where you can't add an id to a view


This also works:

this.getCurrentFocus()

It gets the view so I can use it.


The getParent method returns a ViewParent, not a View. You need to cast the first call to getParent() also:

RelativeLayout r = (RelativeLayout) ((ViewGroup) this.getParent()).getParent();

As stated in the comments by the OP, this is causing a NPE. To debug, split this up into multiple parts:

ViewParent parent = this.getParent();
RelativeLayout r;
if (parent == null) {
    Log.d("TEST", "this.getParent() is null");
}
else {
    if (parent instanceof ViewGroup) {
        ViewParent grandparent = ((ViewGroup) parent).getParent();
        if (grandparent == null) {
            Log.d("TEST", "((ViewGroup) this.getParent()).getParent() is null");
        }
        else {
            if (parent instanceof RelativeLayout) {
                r = (RelativeLayout) grandparent;
            }
            else {
                Log.d("TEST", "((ViewGroup) this.getParent()).getParent() is not a RelativeLayout");
            }
        }
    }
    else {
        Log.d("TEST", "this.getParent() is not a ViewGroup");
    }
}

//now r is set to the desired RelativeLayout.

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-layout

How to check if a key exists in Json Object and get its value How to center the elements in ConstraintLayout Android - how to make a scrollable constraintlayout? Add ripple effect to my button with button background color? This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint Is it possible to put a ConstraintLayout inside a ScrollView? Differences between ConstraintLayout and RelativeLayout How to remove title bar from the android activity? How to have EditText with border in Android Lollipop Android: ScrollView vs NestedScrollView

Examples related to view

Empty brackets '[]' appearing when using .where SwiftUI - How do I change the background color of a View? Drop view if exists Difference between View and ViewGroup in Android How to make a view with rounded corners? How to remove all subviews of a view in Swift? How to get a view table query (code) in SQL Server 2008 Management Studio how to add button click event in android studio How to make CREATE OR REPLACE VIEW work in SQL Server? Android findViewById() in Custom View

Examples related to parent-child

The specified child already has a parent. You must call removeView() on the child's parent first (Android) Example of waitpid() in use? get parent's view from a layout CSS :: child set to change color on parent hover, but changes also when hovered itself How to pass data from 2nd activity to 1st activity when pressed back? - android Make absolute positioned div expand parent div height JavaScript DOM: Find Element Index In Container How to set opacity in parent div and not affect in child div? How to select <td> of the <table> with javascript? Maven: Non-resolvable parent POM