Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android View add child

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!

like image 503
jkigel Avatar asked Jul 19 '12 05:07

jkigel


People also ask

What is a ViewGroup 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. Eg: LinearLayout is a ViewGroup that can contain other views in it.

What is parent and child in Android layout?

Simply you can think of the real life relation between parent and child. on the hierarchy parents are toplevel and child is below.so when you come to android layout parent is container and child is the content.

What is the main purpose of ViewGroup?

What is the main purpose of a ViewGroup? It groups together the most common views that developers use in Android apps. It serves as a container for View objects, and is responsible for arranging the View objects within it. It is required to make a view interactive as a way to group TextViews on a screen.


2 Answers

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.

like image 120
user370305 Avatar answered Oct 24 '22 08:10

user370305


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

like image 24
Maxim Avatar answered Oct 24 '22 09:10

Maxim