Friday, January 9, 2015

Android: Taking control of the orientation...

It can be pretty irritating when you have a mixture of screens that should be only be appearing in a Potrait or a Landscape orientation only. Therefore here's a quick demo to show you how you can take control of the orientation of your Android App.

Here's the source code of the Main Activity of the Android Application - MainActivity.java
package com.nekyoutoTech.controloverorientation;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;

public class MainActivity extends Activity {
 
 //Dummy Array of Buttons
 private Button[] btns = new Button[5];
 
 //Stores a reference of the Application Context
 private static Context context;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  //Loop through the buttons and assign the Click Listener to them
  for(int i = 0; i < 5; i ++){
   int resID = getResources().getIdentifier("btn" + i, "id", getPackageName());
   btns[i] = (Button) findViewById(resID);
   btns[i].setOnClickListener(btnClickListener);
  }
  
  context = this.getApplicationContext();
 }

 /**
  * Upon clicking on any of the buttons
  */
 OnClickListener btnClickListener = new OnClickListener(){
  @Override
  public void onClick(View v) {
   //Get the String of the button first
   Button btn = (Button) v;
   String text = (String) btn.getText();
   
   //Depending on the button that was click, let's select the orientation
   //that we would want to set for the app.
   int orientation;
   if (context.getResources().getString(R.string.btn0Str).equals(text)) {
    orientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR;
   } else if (context.getResources().getString(R.string.btn1Str).equals(text)) {
    orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
   } else if (context.getResources().getString(R.string.btn2Str).equals(text)) {
    orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
   } else if (context.getResources().getString(R.string.btn3Str).equals(text)) {
    orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
   } else if (context.getResources().getString(R.string.btn4Str).equals(text)) {
    orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
   } else {
    orientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR;
   }
   
   //Let's set the orientation of the app now.
         setRequestedOrientation(orientation);
  }
 };
}
* Click here for the source files of the project.