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 -
package com.nekyoutoTech.controloverorientation;

import android.content.Context;
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;

 protected void onCreate(Bundle savedInstanceState) {
  //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);
  context = this.getApplicationContext();

  * Upon clicking on any of the buttons
 OnClickListener btnClickListener = new OnClickListener(){
  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)) {
   } else if (context.getResources().getString(R.string.btn4Str).equals(text)) {
   } else {
    orientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR;
   //Let's set the orientation of the app now.
* Click here for the source files of the project.