jyavenard
jyavenard

Reputation: 2095

Adding Views to another View

Is there a possibility to add a view or derivative (button, textview, imageview etc...) to another view without having to go through layouts?

I have a class called ScreenView, it derives from View (e.g. public class ScreenView extends View). I wanted to display text into it, labels, images etc..

On an iPhone it's trivial, simply create my objects and use addSubview method ; you can embed any UI objects into another. Most UI toolkits work that way too.

Problem with layouts is that I haven't found an easy way to properly position a subview (say a text view) in a given location of the enclosing View. I want one to contain the other...

I was hoping I had missed something in the documentation (which is far from being intuitive that's for sure) and I could do something like myView.addView(subview). But it ain't so :)

As a side question, what is the closest to iPhone's UILabel in the Android world? A UILabel can contain a text or a graphic. Right now I've been using TextView and ImageView but they aren't anywhere as flexible when it comes to layout as a UILabel

Edit: Making my View inherit from ViewGoup instead, let me add subview.. However, I want to draw in my view. I found that when ScreenView extends ViewGroup, the onDraw function is never called then.

Something like:

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);

            Paint paint = new Paint();
            paint.setStyle(Paint.Style.FILL);

            // make the entire canvas yellow
            paint.setColor(Color.YELLOW);
            canvas.drawPaint(paint);
}

Would paint in yellow my view if ScreenView extends View ; but not if it extends ViewGroup.

How do you draw directly in the view then?

Thanks JY

Upvotes: 2

Views: 3118

Answers (2)

jyavenard
jyavenard

Reputation: 2095

After making my class inherit from RelativeLayout instead, it does draw my subviews. GroupView doesn't draw anything by default, and onLayout needs to be fully written. With no documentation on this matter it's going to be a hard thing to do.

onDraw isn't called by default, it does get called if you set the background colour or add any drawable item.

Otherwise you need to draw during dispatchDraw instead.

Upvotes: 0

Romain Guy
Romain Guy

Reputation: 98501

Use a ViewGroup, that's what they are for. And then you can call addView() :)

Upvotes: 1

Related Questions