Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anyone give a good example of a Custom ViewGroup containing a Custom View with measure and layout examples? (In Java)

Tags:

android

I've been having a few issues with using custom viewgroups and custom views. I've done a lot of searching already for this, but if I missed something feel free to link me there. Yes I have read everything about Views, ViewGroups, measure and layout passes on the android dev website, but I'm still confused without any Java sample code.

1)My understanding is that child-views need to implement onMeasure and onLayout. Does this mean that the parent ViewGroup needs to manually call measure() and layout() for each of its children? If so, where should these calls be located? Should they be in the Parent's onMeasure and onLayout methods? If so, where are the very first measure() and layout() calls that start this whole recursive process.

2) I see that layout params of a childview can be set using something like the following. Should this code be place inside the onLayout of the parent viewgroup?

CustomView cust = new CustomView(context);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
cust.setLayoutParams(params);

If I want to set a MeasureSpec, do I just add it as another rule here?

3) Is it okay to create an instance of a CustomView and add it to CustomViewGroup from inside the code for CustomViewGroup, and if so should I put this code in the CustomViewGroup constructor? If not, is it just understood that you create ViewGroups and then add children all from a different outside class?

4)Is it common to practice to call draw() for each of my childviews inside the onDraw() method for CustomViewGroup?

Right now, when I execute some code to draw a circle, it executes the draw method of view but nothing actually appears on the screen. When I add it to a relativeLayout instead of my customViewGroup, I have no problem...So I think I'm missing a key piece about how to get viewgroups to show up. (Yes, I set the ContentView to the ViewGroup).

Thanks in advance!

Edit: Please don't show me XML, I'm doing this all in Java.

like image 989
Laura Avatar asked Apr 28 '11 01:04

Laura


1 Answers

I recommend you to read these slides and watch this video.

like image 192
Romain Guy Avatar answered Oct 21 '22 15:10

Romain Guy