Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Android keep the view object hierarchy in memory?

When I create a button:

@Override
public void onCreate(Bundle savedInstanceState)
{
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   LinearLayout layout = …;

   Button btn = new Button(this);
   btn.setText("My Button");

   layout.addView(btn);
}

If I don't keep a strong reference to the btn, does Android keep the btn instance alive?

For example, does layout.getChildView(0) return the exact instance (btn)? or does Android create and return a new instance of Button and return it?

I'm not talking about subclassing, (e.g. class MyButton extends Button) which I think it's obvious it must be kept in memory, I am only asking about built-in view classes.

like image 584
Don Box Avatar asked Mar 01 '26 03:03

Don Box


1 Answers

ViewGroup stores strong references on its children in an array. If you take a look into ViewGroup sources you find following field:

private View[] mChildren;

And when you call getChildAt you get an instance from this array:

public View getChildAt(int index) {
    if (index < 0 || index >= mChildrenCount) {
        return null;
    }
    return mChildren[index];
}
like image 77
Bracadabra Avatar answered Mar 03 '26 15:03

Bracadabra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!