Android的动态图像大小

4

我面临一个问题,即如何在手机和平板电脑之间保持相同的布局。

原因是我的大多数图片都是固定尺寸的。因此,从手机切换到平板电脑时会出现问题。

我的活动布局如下。

<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

有没有可能像在html中一样给宽度设置百分比而不是固定的dp?这样它可以自动调整到父容器的宽度。

谢谢!


如果您在屏幕宽度上设置了3个相同宽度的图像,则使用layout_weight="1"。并且将layout_width设置为"0dp"。 - Divyang Metaliya
3个回答

7

请尝试以下操作:

步骤1:使用以下代码动态计算设备屏幕的高度和宽度。

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

int screenHeight = displaymetrics.heightPixels;
int screenWidth = displaymetrics.widthPixels;

步骤2:通过使用以下代码,在您的Activity或Fragment中获取ImageView的引用

ImageView myImageView = (ImageView) findViewById(R.id.your_image_view);

第三步: 根据屏幕的高度和宽度来计算您的ImageView的高度和宽度。

假设您想要一个占屏幕10%高度的ImageView; 那么图片的高度应该是

int imgHeight = (int) (screenHeight* 0.10); // 10% of screen.

如果您想将宽度设置为25%,则应该这样做:

int imgWidth =  (int) (screenWidth* 0.25); // 25% of screen.

步骤 4: 最后,通过以下代码在程序中设置 ImageView 的高度和宽度。

myImageView.getLayoutParams().height = imgHeight;
myImageView.getLayoutParams().width = imgWidth;

希望这能帮到你。让我知道吧。

0

如果您在所有图像中设置相同的宽度

 <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:src="@drawable/ic_launcher" />

    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:src="@drawable/ic_launcher" />

    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:src="@drawable/ic_launcher" />
</LinearLayout>

0
  1. 首先尝试在资源文件夹中制作不同大小的图像。
  2. 有时候您也可以使用match-parent和wrap-content。

我认为制作不同大小的相同图像,并将它们放置在res/drawable(hdpi、mdpi等)文件夹中,根据它们的大小进行分类,这样Android会自动从这些文件夹中选择适合设备dpi的图像。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接