简体   繁体   中英

Android How to programatically determine which XML layout my app is using?

I want be be able to log the screen size the app is on to make it easier for me to get the layouts perfect for the different android screen sizes. I have implemented a class called layoutSizeAcitivty with the following code:

    public class LayoutSizeActivity extends SherlockActivity{

public void LayoutSize(){
    //Determine screen size
    if ((getResources().getConfiguration().screenLayout &Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) 
    {     
        Log.d("Screen Size: ", "LARGE");
    }
    else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {     
        Log.d("Screen Size: ", "NORMAL");
    } 
    else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {     
        Log.d("Screen Size: ", "SMALL");
    }
    else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {     
        Log.d("Screen Size: ", "XLARGE");
    }
    else {
        Log.d("Screen Size: ","UNKNOWN_CATEGORY_SCREEN_SIZE");
    }

    //Determine density
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    int density = metrics.densityDpi;

    if (density==DisplayMetrics.DENSITY_HIGH) {
        Log.d("Screen Density: ","HIGH");
    }
    else if (density==DisplayMetrics.DENSITY_MEDIUM) {
        Log.d("Screen Density: ","MEDIUM");
    }
    else if (density==DisplayMetrics.DENSITY_LOW) {
        Log.d("Screen Density: ","LOW");
    }
    else if (density==DisplayMetrics.DENSITY_XHIGH) {
        Log.d("Screen Density: ","XHIGH");
    }
    else if (density==DisplayMetrics.DENSITY_XXHIGH) {
        Log.d("Screen Density: ","XXHIGH");
    }
    else {
        Log.d("Screen Density: ","UNKNOWN_CATEGORY");
    }
}

}

Then in my first activity in the onCreate method I add this:

private LayoutSizeActivity layoutSize;
layoutSize = new LayoutSizeActivity();
layoutSize.LayoutSize();

For some reason my LayoutSizeActivity.LayoutSize() returns a null pointer exception. Anyone got any Ideas to why that is? Thanks

private LayoutSizeActivity layoutSize;
layoutSize = new LayoutSizeActivity();

You can NOT create an instance of an Activity using new . Don't ever try it, it will NEVER work.

The only way you can create an Activity is with startActivity(...) or one of the similar methods such as startActivityForResult(...) etc.

Activity class

Activities Guide

Application Fundamentals

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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