Friday, September 7, 2012

Understanding Layouts in Android

A layout defines the visual structure for a user interface, such as the UI for an activity or app widget. You can declare a layout in two ways:
  • Declare UI elements in XML. Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts.
  • Instantiate layout elements at runtime. Your application can create View and ViewGroup objects (and manipulate their properties) programmatically.




In Android, there are various types of layouts available which are used to design the screen or we can say, are used to arrange the order of various widgets(like- TextView, EditText, Button, Image, ImageButton etc.) in the required manner. In Android terms, the layouts are called as ViewGroups and widgets are called as Views.
The wise use of different layouts in the screen can reduce the development time and effort and even can save you from the later stage issues (like- inserting more widgets in the screen in later stage, porting to different screen resolutions, we will discuss it in the upcoming posts).
So, Lets start understanding the behavior of different layouts:
 

Linear Layout:

 Linear layout arranges all the children widgets in one direction like- vertical or horizontal as shown in the image.
So, where ever we want some widgets to be aligned in a single direction, we can make use of Linear Layout.
Remember that designing the android screen goes from top to down fashion.


Android has given three amazing properties- wrap_content, match_parent, fill_parent to declare the height and width of the layouts and widgets. The one should make use of them very wisely. Never practice declaring the absolute height and width of any view. The best way is to use property wrap_content maximally.

Relative Layout:

 Relative layout arranges the children widgets relative to the parent layout or relative to each other. Best way to understand it, look at the image.
Table Layout: Table layout arranges the children widgets in the table, i.e. rows and columns, look at the image.

Frame Layout:

Frame layout arranges the children widgets relative to top left point. In this way, the widgets may get overlapped as shown in the image.
Absolute Layout: Absolute layout pins the children widgets in the coordinate points as shown in the image.
However, this layout is advised not to practice as it raises the issues while designing the same layout for different screen resolutions. Even it has been deprecated in the latest versions of Android.
Hope you enjoyed.
Comments and Questions are welcome.


Some of contents this post is taken from one of my friend's Deepak Garg Blog

Thursday, September 6, 2012

Android CheckBoxe Example

A checkbox is a specific type of two-states button that can be either checked or unchecked.
We will learn how to use checkbox in this tutorial.


Note: You should  know how to use Buttons and TextViews , if  you do not know then read this post  Using Buttons and TextViews in Android.

Create a new project.
Name your activity "CheckBoxActivity"


Editing main.xml file :


open main.xml file and  add TextViews, CheckBoxes and Buttons, it should like like below. (you can just copy the below code and paste in main.xml file)





main.xml


  <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="vertical" >

   
    
    
     <TextView
         android:text="Choose Your Hobies"
         android:layout_marginTop="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         />

    
     <CheckBox
        android:id="@+id/chkReading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Reading" />

    <CheckBox
        android:id="@+id/chkSong"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Listening Songs"
        android:checked="true" />

    <CheckBox
        android:id="@+id/chkPLay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Playing" />
    
    <CheckBox
        android:id="@+id/chkSing"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Singing" />
    
    <CheckBox
        android:id="@+id/chkDance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Dancing" />
    
    
     <TextView
         android:id="@+id/result"
         android:textSize="20dp"
         android:layout_marginTop="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         />

    <Button
        android:id="@+id/btnDisplay"
        android:layout_marginTop="20dp"
        android:gravity="center_horizontal"
        android:layout_gravity="center_horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="        OK        " />

</LinearLayout>


Thing To Note

 android:checked="true"         you can initially checked any check box using this tag. see  in fig.
 " Listening Song" is already checked.

Editing CheckBoxActivity  file


CheckBoxActivity.java



       public class CheckBoxActivity extends Activity
       {

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView textHobbies=(TextView)findViewById(R.id.result);
// getting refference of check boxes
final CheckBox reading=(CheckBox)findViewById(R.id.chkReading);
final CheckBox playing=(CheckBox)findViewById(R.id.chkReading);
final CheckBox listening=(CheckBox)findViewById(R.id.chkPLay);
final CheckBox singing=(CheckBox)findViewById(R.id.chkSing);
final CheckBox dancing=(CheckBox)findViewById(R.id.chkDance);
// get reffrence of Button
Button button=(Button)findViewById(R.id.btnDisplay);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String hobbies="";
if(reading.isChecked())
hobbies+="Reading";
if(playing.isChecked())
hobbies+="  Playing";
if(listening.isChecked())
hobbies+="  Listening Music";
if(singing.isChecked())
hobbies+="  Singing";
if(dancing.isChecked())
hobbies+="  Dancing";
 textHobbies.setText("Your Hobbies are : "+hobbies) ;
}
});
}

    
    }

Point to Note:

checkBoxObject.isChecked();
isChecked() method returns true if the checkBox is checked , and false otherwise.

Now run your project , do some activity(check or unceck checkboxes)
You will see the following.



Hope you learned and enjoyed
Comments and questions are welcome

                                      



Wednesday, September 5, 2012

Android Tutorials

The Android Development Tutorials blog contains Basic as well as Advanced android tutorials. Learn Android Development by example with this blog.

New Advance Topics:                   Android LiveWallpaer Tutorial
Android ImageSwitcher                    Android TextSwitcher                                Android ViewFlipper
Android Gesture Detector               Handling/Detecting Swap Events                Gradient Drawable
Detecting Missed Calls                    Hide Title Bar                                           GridView Animation
Android AlarmManager                 Android BootReceiver                       Vibrate Phone In a Desirable Pattern    
Developing for Different Screen Sizes           Showing Toast for Longer Time       Publishing your App
How to publish Android App on Google Play

 Beginning With Android
      Android : Introduction(What is Android)                                                 Configuring Eclipse for Android Development
     Creating Your First Android Project                                           Understanding Android Manifest File of your android app

 Advance Android Topics                                                              Customizing Android Views


Working With Layouts                                                                Working With Views

Understanding Layouts in Android                                                   Using Buttons and EditText in Android
Working with Linear Layout (With Example)                                     Android CheckBoxes Example
Nested Linear Layout (With Example)                                              Android  AutoCompleteTextView         Grid View 
Relative Layout In Android                                                               ListView
Table Layout                                                                                   Android ProgressBar
Frame Layout(With Example)                                                          Customizing ProgressBar
Absolute Layout                                                                             Customizing Radio Buttons
Grid Layout                                                                                    Customizing Checkboxes In Android

Android Components                                                                 Dialogs In Android

Activity In Android                                                                    Android Alert Dialog Example
Activity Life Cycle                                                                    Adding Radio Buttons In Dialog
Starting Activity For Result                                                       Adding Check Boxes In Dialog
Sending Data from One Activity to Other in Android                    Creating Customized Dialogs in Android
Returning Result from Activity                                                   Creating Dialog To Collect User Input
Android : Service                                                                     DatePicker and TimePickerDialog
BroadcastReceiver                                                                   Using TimePickerDialog and DatePickerDialog In android

Menus In Android                                                                ListView:
Creating Option Menu                                                               Populating ListView With DataBase
Creating Context Menu In Android                                              Populating ListView with ArrayList
                                                                                               ListView with Custom Adapter

Toast                                                                                      Working With SMS
Customizing Toast In Android                                                       How to Send SMS in Android
Customizing the Display Time of Toast                                        How To Receive SMS
Customizing Toast At Runtime                                                  Accessing Inbox In Android
Adding Image in Toast
Showing Toast for Longer Time


TelephonyManager                                                            Storage: Storing Data In Android
Using Telephony Manager In Android                                          SharedPreferences In Android
                                                                                              Reading and Writing files to Internal Stoarage

Working With Incoming Calls                                       DataBase :  Introduction of SQLiteDataBase
How To Handle Incoming Calls in Android                                Working With Database in Android
How to Forward an Incoming Call In Android                            Creating Table In Android
CALL States In Android                                                          Inserting, Deleting and Updating Records In Table in Android


Miscellaneous
Notifications In Android
How To Vibrate The Android Phone
Sending Email In Android
Opening a webpage In Browser
How to Access PhoneBook In Android
Prompt User Input with an AlertDialog



Sending Data from One Activity to Other in Android

Hi friends
In this post we will learn how to send data(integer,long,string etc) from one activity to other.

Note: I hope you  are familiar with using Buttons and EditTexts if not then go through this post  Using Button and EditText in Android.

Some times while working with android we need to send some data from one Activity to other.
Here we will create a project which will have two activities "FirstActivity" and "Second Activity".
We send Name and Phone Number from  FirstActivity to Second Activity and display the sent data.

Create a new project.

Donot forget to add SecondActivity in manifest.

Editing main.xml file


Edit your main.xml file add two  textviews, two edittexts, and  a button.
It should look like (you can just copy the following xml code and paste in main.xml file)


main.xml



<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="vertical">

    <TextView 
        android:text="Name"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"/>
    
      <EditText 
        android:id="@+id/name"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"/>
      <TextView 
        android:text="Phone Number"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"/>
      <EditText 
        android:id="@+id/phone"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"/>
      <Button 
        android:id="@+id/button"
        android:text="OK"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"/>

</LinearLayout>

Now open the FirstActivity class and write following


 FirstActivity.java


public class FirstActivity extends Activity 
{

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button button=(Button)findViewById(R.id.button);
    final EditText editTextName=(EditText)findViewById(R.id.name);
    final EditText editTExtPhone=(EditText)findViewById(R.id.phone);
   
   
    // add button onClick Listener
    button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String name=editTextName.getText().toString();
long phone=Long.parseLong(editTExtPhone.getText().toString());
// create a new intent
Intent intent =new Intent(getApplicationContext(),SecondActivity.class);
// put the name and phone(to be sent to other activity) in intent
intent.putExtra("PERSON_NAME", name);
intent.putExtra("PHONENUMBER", phone);
// start the second activity
startActivity(intent);
}
});
    }

    
}

Edit your SecondActivity class


Point to Note(To Rememeber)

intent.putExtra("PERSON_NAME", name);
we have put the name in intent with "PERSON_NAME" tag, we will fetch name in second activity with same tag(see second activity).  similarly we can send and fetch any type of data.

SecondActivity.java (Do not forget to declare this activity in manifest file)


public class SecondActivity extends Activity 
{

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// extract the name and phone from intent
String name=getIntent().getStringExtra("PERSON_NAME");
long phoneNumber=getIntent().getLongExtra("PHONENUMBER", 0);
TextView tv=new TextView(this);
tv.setTextSize(20);
String str="NAME : "+name+"\nPhone Number : "+phoneNumber;
tv.setText(str);
setContentView(tv);
}
}


Now run the application, you will see the following




More Android Tutorials


Android : Introduction


       Eclipse Setup for Android Development

                     Configuring Eclipse for Android Development

          Begging With Android

                     Creating Your First Android Project
                     Understanding Android Manifest File of your android app


         Working With Layouts

                      Understanding Layouts in Android
                          Working with Linear Layout (With Example)
                                Nested Linear Layout (With Example)
                          Table Layout
                          Frame Layout(With Example)
                         Absolute Layout
                         Grid Layout


       Activity

                     Activity In Android
                     Activity Life Cycle
                     Starting Activity For Result
                     Sending Data from One Activity to Other in Android
                     Returning Result from Activity

     Working With Views

                     Using Buttons and EditText in Android 
                     Using CheckBoxes in Android 
                     Using AutoCompleteTextView in Android
                     Grid View

     Dialogs In Android

                     Working With Alert Dialog
                     Adding Radio Buttons In Dialog
                     Adding Check Boxes In Dialog
                     Creating Customized Dialogs in Android
                    Adding EditText in Dialog

                   Creating Dialog To Collect User Input

                 DatePicker and TimePickerDialog

                              Using TimePickerDialog and DatePickerDialog In android

    Working With SMS

                  How to Send SMS in Android
                  How To Receive SMS
                  Accessing Inbox In Android

    ListView:

               Populating ListView With DataBase

      Menus In Android

                    Creating Option Menu
                    Creating Context Menu In Android

      TelephonyManager

                    Using Telephony Manager In Android

     Working With Incoming Calls

                    How To Handle Incoming Calls in Android
                    How to Forward an Incoming Call In Android
                   CALL States In Android

    Miscellaneous

                   Notifications In Android
                   How To Vibrate The Android Phone
                   Sending Email In Android
                  Opening a webpage In Browser
                   How to Access PhoneBook In Android
                   Prompt User Input with an AlertDialog

   Storage:  Storing Data In Android


               Shared Prefferences  In Android

                             SharedPreferences In Android

               Files: File Handling In Android

                              Reading and Writing files to Internal Stoarage
                              Reading and Writing files to SD Card 
                         

                DataBase : Working With Database

                             Working With Database in Android
                             Creating Table In Android
                             Inserting, Deleting and Updating Records In Table in Android
                             How to Create DataBase in Android
                             Accessing Inbox In Android

     Animation In Android:

                  Animating A Button In Android