0

我正在尝试创建一个顶部ImageView带有 a的视图。TextView

我一直在努力寻找任何好的例子,所以我希望有人能告诉我我做错了什么或在哪里寻找例子。我看过http://developer.android.com/guide/topics/ui/custom-components.html#compound但只真正描述了最低要求。

我发现了一些东西,比如使用自定义 XML 属性创建复合控件,但我的设置有点不同。

我的代码在下面,它扩展LinearLayout了,我不确定这是否是可行的方法。布局中不显示任何内容。

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);
    }
}

状态.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>
4

1 回答 1

1

使用 RelativeLayout 而不是 LinearLayout,这将允许您将文本放置在图像上。

它们没有出现的原因是它们没有使用 addView 添加,所以在你设置好每个的 LayoutParams 之后调用它。

删除 onDraw() 调用,除非您明确要求,否则它不会用于 ViewGroups。一旦添加了视图,它们就会自动绘制出来。

于 2012-06-21T15:31:15.737 回答