Tuesday, August 19, 2014

Screen Rotation in Android

In this tutorial, we shall see how to adjust the app screen when a user rotates his device. We shall see a simple tutorial to display "Hello World" on the screen and adjust the display depending on user's screen rotation. We shall follow these steps:
i. Put the text in a XML layout
ii. Update the Manifest file to respond to screen rotation
iii. Check the screen orientation and display toast message using Java code to show screen orientation

1. XML layout files

Open the main.xml file and write the following code. 
File: res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity" >
    <TextView android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerHorizontal="true"

        android:layout_centerVertical="true"

        android:text="Hello World" />
</RelativeLayout>

2. Manifest.xml

Open the AndroidManifest.xml file and write the following code.
File: AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.endeavour.tutorial"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.endeavour.tutorial.Main"
            android:label="@string/app_name"
            android:configChanges="orientation|screenSize|keyboardHidden">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
</application>
</manifest>

3. Java Code

We shall create a toast message in Java to display the screen orientation mode.
File: Main.java

package com.endeavour.tutorial;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.widget.Toast;

public class Main extends Activity {
@Override
    protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    //Check screen orientation or screen rotate event here
  @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Toast.makeText(this, "Landscape Mode", Toast.LENGTH_SHORT).show();
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            Toast.makeText(this, "Portrait Mode", Toast.LENGTH_SHORT).show();
}
    }
}

4. Output

The following outputs shall be displayed for the two screen orientations.

i. Portrait Mode


ii. Landscape Mode


Monday, August 11, 2014

Using Clocks in Android

In this tutorial, we shall see how to display clocks in Android - Analog as well as Digital. The Analog clock displays two hands- one for hours and the other for minutes, while digital clock shows the hours, minutes and seconds in a digital format.

Note:- Analog and digital clocks can only be used to display time and cannot modify time. If you wish to modify time, use time picker instead.

1. Add the clocks in XML

Open the main.xml file and add AnalogClock and DigitalClock in XML.
File: res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Analog Clock"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <AnalogClock
        android:id="@+id/analogClock1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Digital Clock"
        android:textAppearance="?android:attr/textAppearanceLarge" />
<DigitalClock
        android:id="@+id/digitalClock1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="DigitalClock" />
</LinearLayout>

2. Java Code

We shall display both the clocks in Java. We are not doing any manipulations out here.
File: Main.java

package com.endeavour.tutorial;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AnalogClock;
import android.widget.DigitalClock;
public class Main extends Activity {
       @Override
       public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
              AnalogClock ac = (AnalogClock) findViewById(R.id.analogClock1);
              //what you wish to do with AnalogClock goes here
              DigitalClock dc = (DigitalClock) findViewById(R.id.digitalClock1);
              //what you wish to do with DigitalClock goes here
       }
}

3. Output

Running the program will show you the following output.


Thursday, August 7, 2014

Use Prompt Dialog in Android

A Prompt Dialog box can be used to prompt the user to enter an input. In this tutorial, we shall enhance the AlertDialog example illustrated previously to enable it to accept user input. This is precisely a custom AlertDialog example.

We shall follow the following steps :
i. Create a prompt dialog layout in XML
ii. Attach the prompt dialog layout to AlertDialog.Builder
iii. Attach the AlertDialog.Builder to AlertDialog

1. XML layout files

We shall use two files- main.xml and custom.xml to display the dialog box, the earlier file shall display the main screen and the latter shall display the prompt dialog.

File : res/layout/main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical">
    <Button android:id="@+id/buttonPrompt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Prompt Dialog" />
<EditText android:id="@+id/editTextResult"
        android:layout_marginTop="15dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
</EditText>
</LinearLayout>

File : res/layout/prompt.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="10dp" >
    <TextView android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Your Message : "
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <EditText android:id="@+id/editTextDialogUserInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
<requestFocus />
</EditText>
</LinearLayout>

2. Java Code

We shall add a listener to the button and set the dialog message.

File: Main.java

package com.endeavour.tutorial;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Main extends Activity {
       final Context context = this;
       private Button button;
       private EditText result;
       public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
              // components from main.xml
              button = (Button) findViewById(R.id.buttonPrompt);
              result = (EditText) findViewById(R.id.editTextResult);
              // add button listener
              button.setOnClickListener(new OnClickListener() {
                     @Override
                     public void onClick(View arg0) {
                           // get prompts.xml view
                           LayoutInflater li = LayoutInflater.from(context);
                           View promptsView = li.inflate(R.layout.prompt, null);
                           AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
                           // set prompt.xml to alertdialog builder
                           alertDialogBuilder.setView(promptsView);
                           final EditText userInput = (EditText) promptsView.findViewById(R.id.editTextDialogUserInput);
                           // set dialog message
                           alertDialogBuilder.setCancelable(false)
                                  .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                      public void onClick(DialogInterface dialog,int id) {
                                         // get user input and set it to result
                                         // edit text
                                         result.setText(userInput.getText());
                                      }
                                    })
                                  .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                      public void onClick(DialogInterface dialog,int id) {
                                         dialog.cancel();
                                      }
                                    });
                           // create alert dialog
                           AlertDialog alertDialog = alertDialogBuilder.create();
                           // show it
                           alertDialog.show();
                     }
              });
       }
}

3. Output

The following output shall be displayed.

i. Home screen with the "Show Prompt Dialog" button


ii. The prompt dialog box appears when the button is pressed


iii. Enter some text and press OK


iv. The text field is filled when "OK" button is pressed