我希望ImageView在不同的屏幕尺寸上看起来相同。为了让您更容易理解它应该如何显示,有一些图像:
最大的问题是我的imageViews是以编程方式创建的。 ImageViews布局和大小由此代码
设置LinearLayout LinearLayoutas = (LinearLayout)findViewById(R.id.LinearLayout);
ImageView ImageViewas = new ImageView(this);
ImageViewas.setScaleType(ImageView.ScaleType.FIT_CENTER);
LinearLayoutas.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
ImageViewas.setLayoutParams(params);
ImageViewas.getLayoutParams().height = 650;
ImageViewas.getLayoutParams().width = 950;
params.setMargins(0, 50, 0, 0);
如何更改此代码的任何想法,我的应用程序在不同的屏幕尺寸上看起来相同?
答案 0 :(得分:2)
好吧,您可以检索设备分辨率并设置imageView
宽度和高度。这是解决方案。
private class ScreenResolution {
int width;
int height;
public ScreenResolution(int width, int height) {
this.width = width;
this.height = height;
}
}
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
ScreenResolution deviceDimensions() {
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
// getsize() is available from API 13
if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return new ScreenResolution(size.x, size.y);
}
else {
Display display = getWindowManager().getDefaultDisplay();
// getWidth() & getHeight() are deprecated
return new ScreenResolution(display.getWidth(), display.getHeight());
}
}
..................
LinearLayout LinearLayoutas = (LinearLayout)findViewById(R.id.LinearLayout);
ImageView ImageViewas = new ImageView(this);
ImageViewas.setScaleType(ImageView.ScaleType.FIT_CENTER);
LinearLayoutas.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
ScreenResolution screenRes = deviceDimensions();
ImageViewas.setLayoutParams(params);
ImageViewas.getLayoutParams().height = screenRes.height;
ImageViewas.getLayoutParams().width = screenRes.width;
params.setMargins(0, 50, 0, 0);
此外,当更改设备方向时,应交换宽度和高度。您可以在onConfigurationChanged
中执行此操作:
@Override
public void onConfigurationChanged(Configuration newConfiguration) {
super.onConfigurationChanged(newConfiguration);
// swap device width and height here and re-assign
}