简体   繁体   English

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

[英]Android resizing based on device screen size

I have the following code called in my Android application. 我在Android应用程序中调用了以下代码。 When I run it on an old Samsung Dart (api < 13), I get a NullPointer exception as noted below. 当我在旧的Samsung Dart(api <13)上运行它时,出现如下所示的NullPointer异常。

Is there a particular reason the code is working for the four lines above it but not the line it is getting the 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);
    }
}

Simply, 只是,

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

webLink is null . webLinknull

Check your layout xml: are you sure the name ( btnWebLink ) is correct? 检查您的布局xml:您确定名称( btnWebLink )是正确的吗? Are you sure you're loading the correct layout xml file? 您确定要加载正确的布局xml文件吗?

Probabily you have the ImageView in one layout but Android is loading the layout for a specific screen size where there's no btnWebLink. 可能您在一个布局中有ImageView ,但是Android正在为没有btnWebLink的特定屏幕尺寸加载布局。

Have a breakpoint in that line and check if the variable webLink is null. 在该行中有一个断点,并检查变量webLink是否为null。

The null pointer exception comes the first time you try to use the variable. 空指针异常是您第一次尝试使用该变量出现异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM