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!
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.
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 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.
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.
You can't add child to view. Only to ViewGroup
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With