我正在尝试将ImageView
与屏幕顶部对齐,并在该图片的左下角显示TextView
。我很难过,有谁知道发生了什么?我希望它看起来像这样(在图形设计器中看起来很好)
这是应用程序中的样子。请注意,图像和屏幕顶部之间有一个很大的空间。
这是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">
</com.package.blah.ImageWithOverlay>
</RelativeLayout>
以下是制作它的代码。
public class ImageWithOverlay extends RelativeLayout {
ImageView image;
TextView text;
int imageHeight;
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
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//super.onMeasure(widthMeasureSpec, heightMeasureSpec);
super.onMeasure(widthMeasureSpec, imageHeight);
}
private void setupDisplay(Context context) {
BitmapDrawable bd = (BitmapDrawable)this.getResources().getDrawable(R.drawable.flowers480);
imageHeight = bd.getBitmap().getHeight();
image = new ImageView(context);
image.setImageDrawable(bd);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
lp.addRule(ALIGN_PARENT_TOP);
image.setLayoutParams(lp);
this.addView(image);
text = new TextView(context);
text.setText("testing");
lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
lp.addRule(ALIGN_PARENT_BOTTOM);
text.setLayoutParams(lp);
this.addView(text);
}
}
感谢任何帮助,如果需要,请随时向我询问更多详细信息。
答案 0 :(得分:1)
我认为您会发现ImageView的大小正确,但图像在视图内缩放并居中。
要修复,请添加:
image.setAdjustViewBounds(true);
要检查此类问题,您可以尝试:
image.setBackgroundColor(0x6600ffff);
这样可以让你看到图像的边界。