我正在尝试创建一个顶部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>