I’m trying to create a view that has an ImageView with a TextView on top of it.
I’m stuck trying to find any good examples on this so I’m hoping someone can tell me what I’ve done wrong or where to look for examples. I’ve seen http://developer.android.com/guide/topics/ui/custom-components.html#compound but only really describes the minimal requirements.
I’ve found a couple things like Creating Compound Controls With Custom XML Attributes but my setup is a tad different.
My code is below, which extends LinearLayout and am not sure if that is even the way to go. Nothing displays in the layout.
ImageWithOverlay
public class ImageWithOverlay extends LinearLayout {
ImageView image;
TextView text;
public ImageWithOverlay(Context context) {
super(context);
setupDisplay(context);
}
public ImageWithOverlay(Context context, AttributeSet attrs) {
super(context, attrs);
setupDisplay(context);
}
public ImageWithOverlay(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setupDisplay(context);
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
image.draw(canvas);
text.draw(canvas);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
private void setupDisplay(Context context) {
image = new ImageView(context);
image.setImageResource(R.drawable.flowers);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
image.setLayoutParams(lp);
text = new TextView(context);
text.setText("testing");
lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
text.setLayoutParams(lp);
}
}
status.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<com.package.blah.ImageWithOverlay
android:id="@+id/imageWithOverlay1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</com.package.blah.ImageWithOverlay>
</RelativeLayout>
Use a RelativeLayout instead of a LinearLayout, this will allow you to place the text over the image.
The reason why they aren’t appearing is that they haven’t been added using addView, so call this after you’ve set each one’s LayoutParams.
Remove the onDraw() call, this isn’t used for ViewGroups unless you explicitly request it do be. And once the Views are added they’ll be drawn automatically.