Is there a way to have two different Java code for one Android app? One targeting phone devices and the other targeting tablet devices.
For example, something like HomeActivity.java and HomeActivity-large.java
Basically I would like to make an Android app that has different layout following its resolution.
I know I can use layout-large to have a specific layout for large devices. I'm not sure how to have a specific logic for tablets and another one for phone targets.
The reason I want to do that is that I would like to make an API call on a screen that I don't want to do on phone.
As an alternative way, I've thought in using a boolean (I'm not sure which one) to test what kind of device the app is running on. But I'm afraid it could get messy.
Another thing could be to make a library with all the functionalities of my app and then two different apps using the library. The problem with that solution is that some code is gonna get replicated.
Any suggestion?
Option 1: To have one project that compiles to one or more applications you need to use Conditional Compile. Basically, something like this
//#ifdef Phone
// do something here
//#else Tablet
// do something else
//#endif
See Java (Eclipse) - Conditional compilation for how to Conditional Compile for Android in Eclipse.
Option 2: You could test for screen size at runtime to determine what UI to show. See:
http://developer.android.com/guide/practices/screens_support.html
xlarge screens are at least 960dp x 720dp
large screens are at least 640dp x 480dp
normal screens are at least 470dp x 320dp
small screens are at least 426dp x 320dp
Different solutions, just the first two that I can imagine:
1) Put on your tablet layouts a view with a specific id and with visible attribute set to GONE. After you inflated the layout, check for the existence of the view with findViewById(...). If the result is null, then you are in a smartphone layout, otherwise you are on a tablet. This approach totally relies on automated system device's resolution detection.
2) Use this code snippet to get the width and height of the screen in pixel, and the decide by yourself what code you execute.
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
Log.d("log", "Screen is " + metrics.widthPixels + "x" + metrics.heightPixels);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With