Android根据屏幕尺寸更改图像大小?

QQW*_*WW1 8 android imageview screen-size

所以我需要根据屏幕区域改变图像的大小.图像必须是屏幕高度的一半,否则它会与某些文本重叠.

所以身高= 1/2屏幕高度.宽度=高度*宽高比(只是试图保持宽高比相同)

我发现了一些东西:

Display myDisplay = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width =myDisplay.getWidth();
int height=myDisplay.getHeight();
Run Code Online (Sandbox Code Playgroud)

但是我如何在java中更改图像高度?甚至是XML,如果可能的话?我似乎找不到合适的答案.

kco*_*ock 17

您可以LayoutParams在代码中执行此操作.不幸的是,没有办法通过XML指定百分比(不是直接,你可以乱用权重,但这并不总是有帮助,它不会保持你的宽高比),但这应该适合你:

//assuming your layout is in a LinearLayout as its root
LinearLayout layout = (LinearLayout)findViewById(R.id.rootlayout);

ImageView image = new ImageView(this);
image.setImageResource(R.drawable.image);

int newHeight = getWindowManager().getDefaultDisplay().getHeight() / 2;
int orgWidth = image.getDrawable().getIntrinsicWidth();
int orgHeight = image.getDrawable().getIntrinsicHeight();

//double check my math, this should be right, though
int newWidth = Math.floor((orgWidth * newHeight) / orgHeight);

//Use RelativeLayout.LayoutParams if your parent is a RelativeLayout
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    newWidth, newHeight);
image.setLayoutParams(params);
image.setScaleType(ImageView.ScaleType.CENTER_CROP);
layout.addView(image);
Run Code Online (Sandbox Code Playgroud)

可能过于复杂,也许有一种更简单的方法?不过这是我第一次尝试的.