Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using View.getParent() in View's constructor

Tags:

android

view

Why doesn't this work?

private ScrollView findScrollParent(View v)
{

    if(v==null)
    {
        return null;
    }
    else if(v instanceof ScrollView)
    {
        return (ScrollView) v;
    }
    else
    {
        return findScrollParent((View)v.getParent());
    }
}

CustomView(Context context, AttributeSet as)
{
     super(context,as);
     ScrollView sv = findScrollParent(this);
}

This is my xml file which is inflated:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_height="fill_parent"
     android:layout_width="fill_parent">
<ScrollView
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <LinearLayout android:layout_height="wrap_content"
        android:layout_width="wrap_content">

       <com.myapp.CustomView android:layout_height="wrap_content"
               android:layout_width="wrap_content"/>

  </LinearLayout>

</ScrollView>
</RelativeLayout>

I want to have a reference to the scrollView in the custom View. My findScrollParent method finds the LinearLayout then returns null. I call this method in the View v's constructor, is that the problem?

like image 476
you786 Avatar asked Aug 17 '11 20:08

you786


People also ask

What is view in xml?

A View occupies a rectangular area on the screen and is responsible for drawing and event handling. Views are used for Drawing Shapes like Circles,Rectangles,Ovals etc . Just Use View with background and apply a Shape using Custom Drawable.

What is view view in java?

A View object in Android app development is the building block for a user interface. They are used to create things onscreen for a user to interact with. http://developer.android.com/guide/topics/ui/overview.html.

What is view view in android?

View is a basic building block of UI (User Interface) in android. A view is a small rectangular box that responds to user inputs. Eg: EditText, Button, CheckBox, etc. ViewGroup is an invisible container of other views (child views) and other ViewGroup.

What is view parent?

Defines the responsibilities for a class that will be a parent of a View. This is the API that a view sees when it wants to interact with its parent.


1 Answers

You can safely access your parent in onAttachedToWindow() method.

See View Life Cycle.

like image 120
LanDenLabs Avatar answered Sep 20 '22 15:09

LanDenLabs