Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FindViewById and multiple layouts for different screen densities (Android)

my question has to do with using different layouts for different screen densities on the Android platform.

Let's say that I have four main.xml files (each in their respective folders for their corresponding screen densities: ldpi, mdpi, hdpi, and xhdpi) and let's say that they're all identical to start with. But let's say I want to get rid of some of the UI elements for the ldpi layout. How do I handle things on the Java side to avoid a null pointer exception when it tries to find that view in the ldpi layout on a ldpi phone? Should I just check and see if findviewbyid returns null and move on from there?

I realize that you're supposed to keep things uniform in your apps, but on occasion it just seems like it'd make more sense to just get rid of a convenient but otherwise unnecessary UI element. I love having the extra real-estate on these new phones, but if/when it comes time to make a ldpi layout, I'd rather not just cram everything in there when it'd look better just to get rid of some stuff, if that makes any sense!

like image 426
Brett Avatar asked Nov 17 '25 03:11

Brett


1 Answers

It is a Good question. Null checking can be one of the solutions. another solution is checking screen properties. look at this example:

public static boolean isTabletPC(Context context) {
        boolean isHoneycomb = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
        boolean hasLargeScreen = (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
        return isHoneycomb & hasLargeScreen;
    }
like image 84
Bobs Avatar answered Nov 19 '25 18:11

Bobs