Android的动态图像大小

Jam*_*Yeo 4 android image imageview

我面临着从Android手机到平板电脑保留相同布局的问题.

原因是因为我的大多数图像都是固定大小的.因此,从手机换成平板电脑时会出现问题.

我的活动布局是这样的.

<relativelayout> - with match_parent for both width and height
     <linearlayout> - with match_parent for both width and height
          <linearlayout> - with match_parent for for width only and match_content for height
                <imageview> - fixed size - 94 dp and 32 dp
Run Code Online (Sandbox Code Playgroud)

是否有可能做类似于给出宽度百分比的东西,就像我们在html中做的那样,而不是修复dp?这样它就可以自动调整到父宽度.

谢谢!

Lav*_*wal 7

请尝试这样的事情:

第1步:使用此代码动态计算设备屏幕的高度和宽度.

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);

int screenHeight = displaymetrics.heightPixels;
int screenWidth = displaymetrics.widthPixels;
Run Code Online (Sandbox Code Playgroud)

第2步:使用此代码在Activity或Fragment中引用ImageView

ImageView myImageView = (ImageView) findViewById(R.id.your_image_view);
Run Code Online (Sandbox Code Playgroud)

第3步:现在根据屏幕的高度和宽度计算ImageView的高度和宽度.

假设您想要与屏幕对应的10%高度ImageView; 然后图像高度应该是

int imgHeight =  screenHeight* 0.10 // 10% of screen.
Run Code Online (Sandbox Code Playgroud)

以同样的方式宽度你想要25%那么它应该是:

int imgWidth =  screenWidth* 0.25 // 25% of screen.
Run Code Online (Sandbox Code Playgroud)

第4步:最后通过此代码设置ImageView的高度和宽度.

myImageView.getLayoutParams().height = imgHeight;
myImageView.getLayoutParams().width = imgWidth;
Run Code Online (Sandbox Code Playgroud)

希望它会对你有所帮助.