有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java布局像素和画布像素不同?

所以,我有一个Framelayout,它有SurfaceView(0)和xml布局(1)。我的布局高度是200px(下图),我正在绘制200px高的矩形以供测试。出于某些奇怪的原因,布局似乎占用了更多的空间。我怎样才能使它成为矩形,而不管屏幕大小或密度如何?(我希望这不会太令人困惑……)

布局:

<LinearLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
xmlns:tools="http://schemas.安卓.com/tools"
安卓:layout_width="match_parent"
安卓:layout_height="200px"
安卓:orientation="horizontal"
安卓:id="@+id/game_ui
"
style="@style/AppTheme">

<LinearLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    安卓:orientation="vertical" 安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    安卓:layout_weight="0.5"
    >

    <TextView
        安卓:layout_width="fill_parent"
        安卓:layout_height="0dp"
        安卓:layout_weight="0.2"
        安卓:text="Points"
        安卓:textSize="30sp"
        安卓:gravity="center"
        />

    <TextView
        安卓:layout_width="fill_parent"
        安卓:layout_height="0dp"
        安卓:layout_weight="0.5"
        安卓:text="500"
        安卓:textSize="60sp"
        安卓:gravity="center"
        />

<LinearLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    安卓:orientation="vertical" 安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    安卓:layout_weight="0.5"
    >
    <TextView
        安卓:layout_width="match_parent"
        安卓:layout_height="0dp"
        安卓:layout_weight="0.2"
        安卓:text="Time"
        安卓:textSize="30sp"
        安卓:gravity="center"
        />

    <TextView
        安卓:layout_width="match_parent"
        安卓:layout_height="0dp"
        安卓:layout_weight="0.5"
        安卓:text="500"
        安卓:textSize="60sp"
        安卓:gravity="center"/>


</LinearLayout>

绘制矩形:

Graphics g = game.getGraphics();
    g.clearScreen(Color.BLACK);   
    g.drawRect(0, 0, wildth, 200, Color.GREEN);
    //draws 200px high rectangle onto surfaceView

结果是:

http://tinypic.com/r/sb6h55/8


共 (1) 个答案

  1. # 1 楼答案

    不要在布局或代码中使用硬编码像素

    在布局中使用与密度无关的像素(DP)

    android:layout_height="200dp" 
    

    将代码中的像素转换为DP

    final int height = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, getResources().getDisplayMetrics());
    final int width = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, getResources().getDisplayMetrics());
    
    Graphics g = game.getGraphics();
    g.clearScreen(Color.BLACK);   
    g.drawRect(0, 0, width, height, Color.GREEN);
    

    欲了解更多信息,请阅读

    http://developer.android.com/guide/practices/screens_support.html#screen-independence