确定Android屏幕尺寸并相应地设置视图的大小

时间:2012-02-26 20:00:19

标签: android android-layout layoutparams

是的,我知道此问题之前已被问过几十次。但是,在实施多个解决方案时,我的应用程序强制关闭。我试过点按一下按钮:

    //Determine Screen Size and Create Layout Param
    android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    int BtnWth = display.getWidth() / 4;
    int BtnHgt = display.getHeight() / 4;
    RelativeLayout.LayoutParams BtnDim = new RelativeLayout.LayoutParams(BtnWth, BtnHgt);

    // Declare MPC pads
    Button pad1 = (Button) findViewById(R.id.pad1);

public void onClick(){

    // Set width and height of each pad
    pad1.setLayoutParams(BtnDim);
}

还使用onDraw()方法。两者都强行关闭真正的Android 3.1设备。

1 个答案:

答案 0 :(得分:4)

尝试使用此代码来获取屏幕宽度和高度(以像素为单位):

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

确保将其添加到导入中:

import android.util.DisplayMetrics;