Android根据设备屏幕大小调整大小

时间:2013-06-20 15:48:16

标签: android

我在Android应用程序中调用了以下代码。当我在旧的三星Dart(api< 13)上运行它时,我得到一个NullPointer异常,如下所示。

代码是否适用于它上面的四行而不是它获取NullPointer的行是否有特殊原因?

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
public void adjustSize() {
    int width, height;

    Display display = getWindowManager().getDefaultDisplay();
    if (android.os.Build.VERSION.SDK_INT >= 13) {
         Point size = new Point();
         display.getSize(size);
         width = size.x;
         height = size.y;
    } else {
        width = display.getWidth();  // deprecated
        height = display.getHeight();  // deprecated
    }

    ImageView counties = (ImageView) findViewById(R.id.btnCounties);
    ImageView members = (ImageView) findViewById(R.id.btnMembers);
    ImageView webLink = (ImageView) findViewById(R.id.btnWebLink);
    ImageView logo = (ImageView) findViewById(R.id.logo);

    // Calculate image sizes
    if (height > width) {
        counties.getLayoutParams().height = (int) (width / 2.5);
        counties.getLayoutParams().width = (int) (width / 2.5);
        members.getLayoutParams().height = (int) (width / 2.5);
        members.getLayoutParams().width = (int) (width / 2.5);

        webLink.getLayoutParams().height = (int) ((width / 2.4) / 3.5);  // Null pointer error 
        webLink.getLayoutParams().width = (int) (width / 2.4);
        logo.getLayoutParams().height = (int) (height / 6);
        logo.getLayoutParams().width = width;
    } else {
        counties.getLayoutParams().height = (int) (height / 2.5);
        counties.getLayoutParams().width = (int) (height / 2.5);
        members.getLayoutParams().height = (int) (height / 2.5);
        members.getLayoutParams().width = (int) (height / 2.5);
    }
}

1 个答案:

答案 0 :(得分:1)

简单地说,

ImageView webLink = (ImageView) findViewById(R.id.btnWebLink);

webLink null

检查你的布局xml:你确定名称( btnWebLink )是否正确?您确定要加载正确的布局xml文件吗?

很可能你在一个版面中有ImageView,但是Android正在加载特定屏幕尺寸的布局,其中没有btnWebLink。

在该行中有一个断点并检查变量webLink是否为空。

空指针异常在您尝试使用该变量时第一次

相关问题