Thursday, August 25, 2011

How to detect a tablet screen in Android

I went to the Android Developer Labs in NYC yesterday. Google talks always kick ass. One of the tips I picked up was how to detect that you are running on a tablet.

We were checking to see if the API level was Honeycomb or newer. This was going to backfire once Ice Cream Sandwich gets released and phones start using newer API levels. It also leaves out the pre-Honeycomb tablets like the popular 7" Galaxy Tab. I'm going to try to push out an update to fix this soon.

The alternative route is a little roundabout but doesn't have either of those problems. You use an id tag in a layout file and only put that tag in layout-large.

res/layout/main.xml

xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent">

LinearLayout>

res/layout-large/main.xml

xml version="1.0" encoding="utf-8"?>

<LinearLayout

xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent">


<FrameLayout android:id="@+id/large_screen_flag"

android:orientation="horizontal" android:layout_weight="2"

android:layout_width="match_parent" android:layout_height="0dp" />

LinearLayout>

Then in your Activity onCreate method:

setContentView(R.layout.main);

boolean isTablet = (null != findViewById(R.id.large_screen_flag));

No comments:

Post a Comment