Skip to content Skip to sidebar Skip to footer

Get Parent's View From A Layout

I have a FragmentActivity with this layout: Copy

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

ViewParentparent=this.getParent();
RelativeLayout r;
if (parent == null) {
    Log.d("TEST", "this.getParent() is null");
}
else {
    if (parent instanceof ViewGroup) {
        ViewParentgrandparent= ((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.

Solution 2:

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;

Solution 3:

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.

Solution 4:

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

Solution 5:

This also works:

this.getCurrentFocus()

It gets the view so I can use it.

Post a Comment for "Get Parent's View From A Layout"