There are three important ways to inherit ViewGroup , so let's take a look at the following:
1.onlayout method
protectedvoidOnLayout (BooleanChangedintLeftintTopintRightintBottom) {
}
When we inherit ViewGroup , we will provide this method in addition to the constructor, and we can see that the method is defined in the source code of ViewGroup , that is, the parent class does not provide the content of the method, we need to implement it ourselves.
This method is called when view wants to allocate size and position for all child objects
2. AddView method
PublicvoidAddView (View child) {
AddView (Child,-1);
}
This method is used to add components to the View container. We can use this method to add components to this viewgroup .
3. Getchildat method
PublicView Getchildat (intIndex) {
Try{
returnMchildren[index];
}Catch(Indexoutofboundsexception ex) {
returnNULL;
}
}
This method is used to return the view at the specified location.
Note: ViewGroup in the View is from 0 start counting.
We can say that these three methods are critical when we customize ViewGroup, so let's take a look at the custom viewgroup use.
We built a project called Androidviewgroup, the activity named Mainactivity. Write a class that inherits from ViewGroup, called Helloviewgroup.
-->helloviewgroup Class
PublicclassHelloviewgroupextendsViewGroup {
PublicHelloviewgroup (context context, AttributeSet Attrs) {
Super(context, attrs);
//TODO auto-generated Constructor stub
}
PublicHelloviewgroup (Context context) {
Super(context);
//TODO auto-generated Constructor stub
}
@Override
protectedvoidOnLayout (BooleanChangedintLintTintRintb) {
//TODO auto-generated Method Stub
}
}
-->mainactivity class
PublicclassMainactivityextendsActivity {
/**Called when the activity is first created.*/
PublicvoidOnCreate (Bundle savedinstancestate) {
Super. OnCreate (Savedinstancestate);
Setcontentview (NewHelloviewgroup ( This));
}
}
At this point you can run, found that the screen in addition to the status bar of the label is a piece of black, hehe. Let's change the code to make our own viewgroup fire up.
We create a new method called Myaddview, which is used to add components to the ViewGroup:
/**
* How to add a view
* */
PublicvoidMyaddview () {
ImageView Micon =NewImageView (Mcontext);
Micon.setimageresource (R.drawable.haha);
AddView (Micon);
}
Then we modify the onlayout method:
@Override
protectedvoidOnLayout (BooleanChangedintLintTintRintb) {
View v = getchildat (0);
V.layout (L, T, R, b);
}
Three ways to ViewGroup