jueves, 6 de noviembre de 2014

Android: Activity orientation

Create a base class from which your activities will inherit
public class AbstractActivity extends Activity {
 
 ...
 
 @Override
 protected void onCreate(Bundle arg0) {

     super.onCreate(arg0);
     
     setOrientationAccordingToDevice();
 }

 ...

 protected void setOrientationAccordingToDevice() {

        if (ScreenHelper.isDeviceATablet(this)) {
            // Since it is a tablet it will have an api > 8. So this is safe.
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
        }
        else {
            // How do I implement the SCREEN_ORIENTATION_SENSOR_PORTRAIT functionality previous to api 9?
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }
}
ScreenHelper
public class ScreenHelper {

 public static boolean isDeviceATablet(Activity activity) {

  DisplayMetrics metrics = new DisplayMetrics();
  activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);

  int widthPixels = metrics.widthPixels;
  int heightPixels = metrics.heightPixels;

  float scaleFactor = metrics.density;

  float widthDp = widthPixels / scaleFactor;
  float heightDp = heightPixels / scaleFactor;

  float smallestWidth = Math.min(widthDp, heightDp);

  return (smallestWidth >= 600);
 }
 
 public static void hideSoftKeyboard(Activity activity, View view) {

  InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
  imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
 }
}

No hay comentarios:

Publicar un comentario