【问题标题】:Getting dimension of a device [closed]获取设备的尺寸[关闭]
【发布时间】:2013-12-27 13:11:07
【问题描述】:

有没有办法获取android设备的宽度和高度并在XML文件中使用它们? 我的目标是为小屏幕和大屏幕制作一个动态应用程序。

【问题讨论】:

    标签: android xml


    【解决方案1】:

    您可以通过编程方式完成并在代码中使用。

    DisplayMetrics displaymetrics = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay()
                .getMetrics(displaymetrics);
        int screenHeight = displaymetrics.heightPixels;
        int screenWidth = displaymetrics.widthPixels;
    

    【讨论】:

      【解决方案2】:

      如果您将高度和宽度设置为填充父级。然后它会占用整个设备屏幕的高度和宽度。

      像这样:

      android:height="fill_parent"
      android:width="fill_parent"
      

      已编辑:

      如果您想使用 20%。然后将父布局的android:weightSum设置为5.0,子父layout:weight="1.0"如下:

      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/main_rel"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="horizontal"
              android:weightSum="5.0" >
      
              <RelativeLayout
                  android:id="@+id/child_one"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:layout_weight="1.0"
                  android:background="#0000FF" >
              </RelativeLayout>
      
              <RelativeLayout
                  android:id="@+id/child_two"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:layout_weight="1.0"
                  android:background="#00FF00" >
              </RelativeLayout>
      
          </LinearLayout>
      

      它将设置适合每个屏幕尺寸的布局。

      【讨论】:

      • 我想使用数字,例如 20% 的屏幕宽度
      • @Branky 查看编辑部分。
      【解决方案3】:
      Display mDisplay = activity.getWindowManager().getDefaultDisplay();
      int width  = mDisplay.getWidth();
      int height = mDisplay.getHeight();
      

      这样你就可以得到屏幕大小。

      【讨论】:

      • 但我不能在 XML 文件中使用它们。
      • 无法在 xml 中查询屏幕尺寸
      • 别无选择?
      【解决方案4】:

      在 res 文件夹中以 values-mdpi、values-hdpi 等名称创建文件夹。 Android 将在运行时加载正确的文件。您可以创建多种类型的文件以供参考 Link

      【讨论】:

        【解决方案5】:

        您可以使用以下代码计算显示尺寸。你可以找到它Here- get screen size in pixels

        然后根据你的尺寸做不同的布局。已解释Here- resize-your-image-according-to-screen-sizes

        希望对你有帮助

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-17
          • 1970-01-01
          • 2011-09-29
          • 2016-12-29
          • 1970-01-01
          • 2019-04-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多