Linear Layout Example

Whats up Geeks,

In the last tutorial we have seen about Custom Dialog Example.

Now in this tutorial we are going to see the example for Linear Layout.

What is Linear Layout?

For the explanation you can refer to this link (Linear Layout).

Starting with the layout placed at

/res/layout/activity_linear_layout.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center"
    android:orientation="vertical"
    tools:context=".LinearLayout" >
   
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:paddingLeft="10px"
        android:paddingTop="20px"
        android:text="LOGIN" />
   
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingTop="20px">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="10px"
            android:paddingTop="20px"
            android:text="Username" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.50"
            android:layout_marginLeft="40px"
            android:paddingTop="20px" />
    </LinearLayout>
   
    <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:paddingTop="20px"
     >
   
                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Password"
                            android:paddingTop="20px"
                            android:paddingLeft="10px"/>
                       
                        <EditText
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_horizontal"
                            android:layout_marginLeft="40px"
                            android:layout_weight="0.50"
                            android:paddingTop="20px" />

    </LinearLayout>
   
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:paddingLeft="20px"
        android:paddingTop="10px"
        android:text="BUTTON" />

</LinearLayout>




LinearLayout.java file placed at

/src/in/geeksandroids/linearlayout/


package in.geeksandroids.linearlayout;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class LinearLayout extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_linear_layout);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_linear_layout, menu);
        return true;
    }
}


Finally AndroidManifest.xml

placed at root folder

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.geeksandroids.linearlayout"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="in.geeksandroids.linearlayout.LinearLayout"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>



After running as Android Application it will show you like this :



See ya in the next tutorial.


Custom Dialog Example

Whats up Geeks,

In the last tutorials we have seen all the theory kind of stuffs. Now we are going to learn Android App Development with examples.

So starting first, in this tutorial we are going learn how to build a Custom Dialog Box with an example and sample code.

Firstly, we need to see what is a dialog?

A dialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed.

Now the question comes how to create a Dialog Box?

Creating a Dialog Box includes two steps:

1> Create a layout with proper ids.
2> Accessing the layout with ids defined.

For example:

Step 1:

in /res/layout/dialog.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageView
        android:id="@+id/imageDialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="6dp" />

    <TextView
        android:id="@+id/textDialog"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#FFF"
        android:layout_toRightOf="@+id/imageDialog"/>

     <Button
        android:id="@+id/declineButton"
        android:layout_width="100px"
        android:layout_height="wrap_content"
        android:text=" Submit "
        android:layout_marginTop="5dp"
        android:layout_marginRight="5dp"
        android:layout_below="@+id/textDialog"
        android:layout_toRightOf="@+id/imageDialog"
        />
    
</RelativeLayout>

Step 2:

Code in .java file
final Dialog dialog = new Dialog(CustomDialog.this);
// define new dialog for CustomDialog Activity
dialog.setContentView(R.layout.dialog);
// Define the layout
dialog.setTitle("Custom Dialog");
// Define the Title

Complete Example is :


/src/in/geeksandroids/customdialog/CustomDialog.java


package in.geeksandroids.customdialog;

import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;


public class CustomDialog extends Activity {

    private Button buttonClick;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_dialog_main);

        buttonClick = (Button) findViewById(R.id.buttonClick);

        // add listener to button
        buttonClick.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                // custom dialog
                final Dialog dialog = new Dialog(CustomDialog.this);
                dialog.setContentView(R.layout.dialog);
                dialog.setTitle("Custom Dialog");

                // set the custom dialog components - text, image and button
                TextView text = (TextView) dialog.findViewById(R.id.textDialog);
                text.setText("Custom dialog Android example.");
                ImageView image = (ImageView) dialog.findViewById(R.id.imageDialog);
                image.setImageResource(R.drawable.image0);

                dialog.show();
               
                Button declineButton = (Button) dialog.findViewById(R.id.declineButton);
                // if button is clicked, close the custom dialog
                declineButton.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });

            }

        });

    }

}



/res/layout/custom_dialog_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:orientation="vertical" >

    <Button
        android:id="@+id/buttonClick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click To Show Custom Dialog" />
 </LinearLayout>

/res/layout/dialog.xml


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

    <ImageView
        android:id="@+id/imageDialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="6dp" />

    <TextView
        android:id="@+id/textDialog"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#FFF"
        android:layout_toRightOf="@+id/imageDialog"/>

     <Button
        android:id="@+id/declineButton"
        android:layout_width="100px"
        android:layout_height="wrap_content"
        android:text=" Submit "
        android:layout_marginTop="5dp"
        android:layout_marginRight="5dp"
        android:layout_below="@+id/textDialog"
        android:layout_toRightOf="@+id/imageDialog" />

</RelativeLayout>

/res/values/strings.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">CustomDialogApp</string>
</resources>


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.geeksandroids.customdialog"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name="in.geeksandroids.customdialog.CustomDialog" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>


When you run the code in eclipse you will get a Custom Dialog Box.

That's all Geeks. See ya in the next tutorial with some other useful examples.


Starting Another Activity

Whats up Geeks,

After learning from our previous tutorials we are now enough capable to launch another Activity from one Activity.

In this tutorial we are going to do this by a button click. We are going to define another Activity when a button is clicked.

We are going to define an app that shows a single screen with a text field and a button. In this lesson, you’ll add some code to MainActivity that starts a new activity when the user clicks the Send button. On  Button click we are going to perform DisplayMessageActivity displaying the message from first Screen.

Respond to the Send Button

In order to respond to the button's on-click event, open the fragment_main.xml layout file and add the android:onClick attribute to the <Button> element:
 
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="sendMessage" />
 
The android:onClick attribute’s value, "sendMessage", is the name of a method in our activity that the system calls when the user clicks the button.

Now we open the MainActivity class (located in the project's src/ directory) and add the corresponding method:

/** Called when the user clicks the Send button */
public void sendMessage(View view) {
    // Do something in response to button
}

In order for the system to match this method to the method name given to android:onClick, the signature must be exactly as shown. Specifically, the method must:
  • Be public
  • Have a void return value
  • Have a View as the only parameter (this will be the View that was clicked)
Next, we’ll fill in this method to read the contents of the text field and deliver that text to another activity.

Now Build an Intent

An Intent is an object that provides runtime binding between separate components (such as two activities). The Intent represents an app’s "intent to do something." We can use intents for a wide variety of tasks, but most often they’re used to start another activity.
Inside the sendMessage() method, create an Intent to start an activity called
DisplayMessageActivity:

Intent intent = new Intent(this, DisplayMessageActivity.class);
 
This requires that us import the Intent class:
 
import android.content.Intent;

Tip: In Eclipse, press Ctrl + Shift + O to import missing classes (Cmd + Shift + O on Mac).
The constructor used here takes two parameters:
  • A Context as its first parameter (this is used because the Activity class is a subclass of Context)
  • The Class of the app component to which the system should deliver the Intent (in this case, the activity that should be started)
An intent not only allows us to start another activity, but it can carry a bundle of data to the activity as well. Inside the sendMessage() method, use findViewById() to get the EditText element and add its text value to the intent:

Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
 
 
In order for the next activity to query the extra data, we should define the key for our intent's extra using a public constant. So add the EXTRA_MESSAGE definition to the top of the MainActivity class:

public class MainActivity extends ActionBarActivity {
    public final static String EXTRA_MESSAGE = "in.geeksandroids.hello.MESSAGE";
    ...
}
 
It's generally a good practice to define keys for intent extras using our app's package name as a prefix. This ensures they are unique, in case our app interacts with other apps.

Coming down next question is how to start the second Activity?
To start an activity, call startActivity() and pass it our Intent. The system receives this call and starts an instance of the Activity specified by the Intent.

With this new code, the complete sendMessage() method that's invoked by the Send button now looks like this:

/** Called when the user clicks the Send button */
public void sendMessage(View view) {
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}
Now we need to create the DisplayMessageActivity class in order for this to work.

How to create the second Activity?

Below steps let us know how to create the second Activity:

To create a new activity using Eclipse:
  1. Click New in the toolbar.
  2. In the window that appears, open the Android folder and select Android Activity. Click Next.
  3. Select BlankActivity and click Next.
  4. Fill in the activity details:
    • Project: Hello
    • Activity Name: DisplayMessageActivity
    • Layout Name: activity_display_message
    • Fragment Layout Name: fragment_display_message
    • Title: My Message
    • Hierarchial Parent: in.geeksandroids.hello.MainActivity
    • Navigation Type: None
    Click Finish.
The DisplayMessageActivity class should now look like this:
 
public class DisplayMessageActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_message);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() { }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                  Bundle savedInstanceState) {
              View rootView = inflater.inflate(R.layout.fragment_display_message,
                      container, false);
              return rootView;
        }
    }
}
If we used an IDE other than Eclipse, update our DisplayMessageActivity class with the above code.

Add the title string

If we used Eclipse, we can skip to the next section, because the template provides the title string for the new activity.
If we're using an IDE other than Eclipse, add the new activity's title to the strings.xml file:
<resources>
    ...
    <string name="title_activity_display_message">My Message</string>
</resources>

Add it to the manifest

All activities must be declared in our manifest file, AndroidManifest.xml, using an <activity> element.
When we use the Eclipse tools to create the activity, it creates a default entry. If we're using a different IDE, we need to add the manifest entry yourself. It should look like this:
<application ... >
    ...
    <activity
        android:name="in.geeksandroids.hello.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="in.geeksandroids.hello.MainActivity" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="in.geeksandroids.hello.MainActivity" />
    </activity>
</application>


Receive the Intent

In the DisplayMessageActivity class’s onCreate() method, get the intent and extract the message delivered by MainActivity:

Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); 
 

Display the Message

To show the message on the screen, create a TextView widget and set the
text using setText(). Then add the TextView as the root view of the activity’s layout by passing it to setContentView().
The complete onCreate() method for DisplayMessageActivity now looks like this:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Get the message from the intent
    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

    // Create the text view
    TextView textView = new TextView(this);
    textView.setTextSize(40);
    textView.setText(message);

    // Set the text view as the activity layout
    setContentView(textView);
}

We can now run the app. When it opens, type a message in the text field, click Send, and the message appears on the second activity.

That's all Geeks, see ya in the next tutorial with some new learnings.


Adding a Button and Input Box

Whats up Geeks,

Till now we have learned about the following including the last tutorial on Adding a String Resources:

> About Android.
> Android SDK Installation.
> Setting Up Android Bundle and Adding Platform and Packages.
> Setting Up Environment for App Development.
> About Android Layouts including Creating Linear Layout, Relative Layout, Grid View.
> Adding a Text Field.


So Geeks, now we are going to learn about Adding a Button and a Input Box during our Android App Development phase.

Firstly, we are going to learn Adding a Button.

Now add a <Button> to the layout, immediately following the <EditText> element:
  
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_send" />
 
The height and width are set to "wrap_content" so the button is only as big as necessary to fit the button's text. This button doesn't need the android:id attribute, because it won't be referenced from the activity code.


So in this way we can add a button to our in the fragment_main.xml file.


The layout is currently designed for both EditText and Button widget as big as necessary to fit their content as shown in below figure:


Figure: The EditText and Button widgets have their widths set to "wrap_content".

This works fine for the button, but not as well for the text field, because the user might type something longer.

So, it would be nice to fill the unused screen width with the text field.

We can do this inside a LinearLayout with the weight property, which we can specify using the android:layout_weight attribute.

The weight value is a number that specifies the amount of remaining space each view should consume, relative to the amount consumed by sibling views.

The default weight for all views is 0, so if we specify any weight value greater than 0 to only one view, then that view fills whatever space remains after all views are given the space they require. So, to fill the remaining space in your layout with the EditText element, give it a weight of 1 and leave the button with no weight.

    <EditText
        android:layout_weight="1"
        ... />
 
In order to improve the layout efficiency when you specify the weight, we should change the width of the EditText to be zero (0dp). Setting the width to zero improves layout performance because using "wrap_content" as the width requires the system to calculate a width that is ultimately irrelevant because the weight value requires another width calculation to fill the remaining space.

    <EditText
        android:layout_weight="1"
        android:layout_width="0dp"
        ... />
 


Figure: The EditText widget is given all the layout weight, so fills the remaining space in the LinearLayout.

Here’s how our complete layout file should now look:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="horizontal">
    <EditText android:id="@+id/edit_message"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_send" />
</LinearLayout>

This layout is applied by the default Activity class that the SDK tools generated when we created the project, so we can now run the app to see the results:


In this way we can design our fragment_main.xml file.

See ya in the next tutorial geeks.

Adding a String Resources

Whats up Geeks,

In the last tutorial we  have learned Adding a Text Field.

In this tutorial we are going to learn Adding a String Resources.

So the question comes what is the use of String Resources addition?

And the answer is :
When we need to add text in the user interface, we should always specify each string as a resource.

Now the question arise what this String resources do?

And the answers is:
String resources allow  to manage all UI text in a single location, which makes it easier to find and update text. Externalizing the strings also allows you to localize your app to different languages by providing alternative definitions for each string resource.

Where does these String resides?

By default, your Android project includes a string resource file at res/values/strings.xml.

Add a new string named "edit_message" and set the value to "Enter a message." (You can delete the "hello_geeks" string.)

While you’re in this file, also add a "Send" string for the button you’ll soon add, called "button_send".

For example:
The result for strings.xml looks like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Hello Geeks</string>
    <string name="edit_message">Enter a message</string>
    <string name="button_send">Send</string>
    <string name="action_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
</resources>


That's all  for today. See ya tomorrow with some new learnings.

Adding a Text Field

Whats up Geeks,

In the last tutorial we have learned Creating Grid View.

Going forward, in this tutorial we are going to learn Adding a Text Fields.

First of all what is Text Fields?

And the answer is "A text field allows the user to type text into your app. It can be either single line or multi-line. Touching a text field places the cursor and automatically displays the keyboard."





How to create a Text Fields?

To create a user-editable text field, add an <EditText> element inside the <LinearLayout>.
Like every View object, you must define certain XML attributes to specify the EditText object's properties.

Below is the declaration of <EditText> it inside the <LinearLayout> element:
    <EditText android:id="@+id/edit_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message" />
About these attributes:
android:id
This provides a unique identifier for the view, which you can use to reference the object from your app code, such as to read and manipulate the object (you'll see this in the next lesson). The at sign (@) is required when you're referring to any resource object from XML. It is followed by the resource type (id in this case), a slash, then the resource name (edit_message).
android:layout_width and android:layout_height
Instead of using specific sizes for the width and height, the "wrap_content" value specifies that the view should be only as big as needed to fit the contents of the view. If you were to instead use "match_parent", then the EditText element would fill the screen, because it would match the size of the parent LinearLayout. For more information, see the Layouts guide.
android:hint
This is a default string to display when the text field is empty. Instead of using a hard-coded string as the value, the "@string/edit_message" value refers to a string resource defined in a separate file. Because this refers to a concrete resource (not just an identifier), it does not need the plus sign. 
 

Creating Grid View

Whats Up Geeks,

In the last tutorial we have seen Creating Relative Layout.

In this tutorial we are going to learn how to create Grid View?

So the question comes how to display items in a two-dimensional scrollable grid.
And the answers id through Grid View.
GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid. The grid items are automatically inserted to the layout using a ListAdapter.


 

For Example:
In open the res/layout/main.xml file and insert the following: 
<?xml version="1.0" encoding="utf-8"?> 
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridview"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:columnWidth="90dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
/>


See you guys in the next tutorial on Adding a Text Field.