Android View add child

21,212

Solution 1

Instead of View use ViewGroup to extend your CustomView class..

A ViewGroup is a special view that can contain other views (called children.) The view group is the base class for layouts and views containers.

Something Like,

public class MyView extends ViewGroup

Now, you can use method called

public void addView (View child)

Adds a child view. If no layout parameters are already set on the child, the default parameters for this ViewGroup are set on the child.

Solution 2

You can't add child to view. Only to ViewGroup

Share:
21,212
jkigel
Author by

jkigel

Updated on July 19, 2020

Comments

  • jkigel
    jkigel almost 4 years

    I have the following View and TextView, How can I add the TextView to the View as it's child ?

    public class MyView extends View {
    
        public MyView(Context context, AttributeSet attrs) {
            super(context);
    
            TextView textView = new TextView(context);
            textView.setText("Hello My Friends");
    
        }
    }
    

    Thanks!