Reputation: 141
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!
Upvotes: 3
Views: 593
Reputation: 64429
From api lvl 11 you would probably want to use fragments for that. This way your java code always deals with views that are definately there, and your layout can show (or not) certain fragments that take care of their own business.
I would advice against littering your code with checks for what kind of screen you have, and checking if a certain view might be in the screen.
If you look at figure one on the linked page, you see a clear example of what i mean:
Upvotes: 0
Reputation: 23010
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;
}
Upvotes: 2
Reputation: 15774
This is handled the same way as handling any optional element. Check if it exists (not null) and handle accordingly. In case of a non-existent View
, findViewById
will return null and you can operate further on the View
inside a if(null != view){}
block or if there are multiple optional elements that can be grouped, you can use an instance variable.
HoneycombGallery demo gives an idea of how you can detect device properties using layouts (although in the demo, it is done for fragments, it can be applied for any View)
Upvotes: 0