Sunday, March 2, 2014

Make stylish Button in android.

Write the below code in string.xml file.


<style name="ButtonText">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textColor">#ffffff</item>
    <item name="android:gravity">center</item>
    <item name="android:layout_margin">3dp</item>
    <item name="android:textSize">30sp</item>
    <item name="android:textStyle">bold</item>
    <item name="android:shadowColor">#000000</item>
    <item name="android:shadowDx">1</item>
    <item name="android:shadowDy">1</item>
    <item name="android:shadowRadius">2</item>
</style>

Make a file named btn_black.xml in drawable folder.


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#343434" />
            <stroke
                android:width="1dp"
                android:color="#171717" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#343434"
                android:endColor="#171717"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#171717" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>

in main.xml


<Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/ButtonText"
        android:background="@drawable/btn_black"
        android:text="@string/add" />

Output:


Friday, February 28, 2014

Example of scrollview in android.

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
  android:layout_height="wrap_content">
 
  <TableLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="0">
   
    <TableRow>
      <View
        android:layout_height="90dp"
        android:background="#000000"/>
    </TableRow>
   
    <TableRow>
      <View
        android:layout_height="90dp"
        android:background="#440000" />
    </TableRow>
   
    <TableRow>
      <View
        android:layout_height="90dp"
        android:background="#884400" />
    </TableRow>
   
    <TableRow>
      <View
        android:layout_height="90dp"
        android:background="#aa8844" />
    </TableRow>
   
    <TableRow>
      <View
        android:layout_height="90dp"
        android:background="#ffaa88" />
    </TableRow>
   
    <TableRow>
      <View
        android:layout_height="90dp"
        android:background="#ffffaa" />
    </TableRow>
   
    <TableRow>
      <View
        android:layout_height="90dp"
        android:background="#ffffff" />
      </TableRow>
  </TableLayout>
</ScrollView>

Output:

Thursday, February 27, 2014

Example of how to pick an image from gallary.

acivity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
 
    <ImageView
        android:contentDescription="@string/hello_world"
        android:id="@+id/imgView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="0"
        android:text="@string/cp" />
 
</LinearLayout>

MainActivity.java


package com.mahi.imagepicker;

import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {

private static int RESULT_LOAD_IMAGE = 1;

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

Button b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(new View.OnClickListener() {
           
            @Override
            public void onClick(View arg0) {
               
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
               
                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
}

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
       
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
           
            ImageView imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
       
        }
    }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

Output:




Sunday, February 23, 2014

Android ImageSwitcher.

activity_main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

 
   <ImageSwitcher
            android:id="@+id/imageSwitcher"
            android:layout_marginTop="50dp"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:layout_gravity="center_horizontal" />
 
      <Button
          android:id="@+id/buttonNext"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:layout_marginTop="150dp"
          android:text="@string/nxt" />
   
</LinearLayout>

MainActivity.java


package com.mahi.imageswitcher;

import android.os.Bundle;
import android.app.Activity;
import android.support.v4.widget.DrawerLayout.LayoutParams;
import android.view.Menu;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;

public class MainActivity extends Activity {

private ImageSwitcher imageSwitcher;
    Button btnNext;
    int imageIds[]={R.drawable.image1,R.drawable.image2,R.drawable.image3,R.drawable.image4,R.drawable.image5,R.drawable.image6,};
    int messageCount=imageIds.length;
    int currentIndex=-1;


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

        btnNext = (Button) findViewById (R.id.buttonNext);
        imageSwitcher = (ImageSwitcher) findViewById (R.id.imageSwitcher);

        imageSwitcher.setFactory(new ViewFactory()
        {
public View makeView() {
                    ImageView imageView = new ImageView(getApplicationContext());
                    imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                    imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
                    return imageView;
            }
        });

        Animation in = AnimationUtils.loadAnimation(this,android.R.anim.fade_in);
        Animation out = AnimationUtils.loadAnimation(this,android.R.anim.fade_out);
       
        imageSwitcher.setInAnimation(in);
        imageSwitcher.setOutAnimation(out);

        btnNext.setOnClickListener(new View.OnClickListener() {
           
            public void onClick(View v) {
                // TODO Auto-generated method stub
                 currentIndex++;
                   // If index reaches maximum reset it
                    if(currentIndex==messageCount)
                        currentIndex=0;
                    imageSwitcher.setImageResource(imageIds[currentIndex]);
            }
        });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Output:



Thursday, February 20, 2014

android:ems attribute in EditText

The em is simply the font size.

In an element with a 2in font, 1em thus means 2in. Expressing sizes, such as margins and paddings, in em means they are related to the font size, and if the user has a big font (e.g., on a big screen) or a small font (e.g., on a handheld device), the sizes will be in proportion.

Declarations such as 'text-indent: 1.5em' and 'margin: 1em' are extremely common in CSS.

Wednesday, February 19, 2014

putExtra() in android

If you want add information to your intent you can use this method.
This information is represented as tuple (key, value).

There are the number of value types that can be included into the extras of intent (for instance, int, int[], Bundle, Parcelable, and so on). For each this method there is a corresponding"read" method that is used to get the information from the intent.

So here is a possible example how to use this.

Imagine that you want explicitly call the activity B from activity A and pass to it an array of integers:

int intArray[]={1,2,3,4};
Intent in=new Intent(this, B.class);
in.putExtra("my_array", intArray);
startActivity(in);

To read the information in activity B (in onCreate() method) you should use the following code:

Bundle extras = getIntent().getExtras();
int[] arrayInB = extras.getIntArray("my_array");

Tuesday, February 18, 2014

Adding the image to the layout.

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

<ImageView
    android:id=”@+id/icon”
    android:layout_width=”wrap_content”
    android:layout_height=”wrap_content”
    android:layout_gravity=”center_horizontal”
    android:src=”@drawable/mahi5” />

</LinearLayout>

An ImageView allows you to project an image to the device’s screen.

android:id=”@+id/icon”


The id attribute defines the unique identifier for the view in the Android system.

layout_gravity


This property defines how to place the view, both its x- and y-axis, with its parent. Here, I have defined the value as the center_horizontal constant. This value informs the Android system to place the object in the horizontal center of its container, not changing its size. You can use many other constants, such as center_vertical, top, bottom, left, right, and many more.

android:src=”@drawable/mahi5”


This property is a direct child of the ImageView class. You use this property to set the image that you would like to show up on the screen.

Viewing XML layout attributes.

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

xmlns:android=” ”


This defines the XML namespace that you will use to reference part of the Android SDK.

orientation=”vertical”


This informs Android that this view is to be laid out in a vertical fashion (like portrait format in printing).

android:layout_width=”fill_parent”


This informs the view that it should fill as much horizontal space as it can, up to its parent. In short, it should make the width as wide as it can be within the parent.

android:layout_height=”fill_parent”


This informs the view that it should fill as much vertical space as it can, up to its parent. In short, it should make the height as tall as it can be within the parent.

Android SDK Layouts

LinearLayout :-


A layout that arranges its children in a single row.

RelativeLayout :-


A layout where the positions of the children can be described in relation to each other or to the parent.

FrameLayout :-


This layout is designed to block out an area on the screen to display a single item. You can add multiple children to a FrameLayout, but all children are pegged to the upper left of the screen. Children are drawn in a stack, with the most recently added child at the top of the stack.This layout is commonly used as a way to lay out views in an absolute position.

TableLayout :-


A layout that arranges its children into rows and columns.

Sunday, February 16, 2014

ProgressBar Example in Android.

activity_main.xml

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

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:indeterminate="false"
        android:max="10"
        android:padding="4dip" >
    </ProgressBar>
   
   <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" >
      </TextView>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="startProgress"
        android:text="@string/sp" >

    </Button>

</LinearLayout>


MainActivity.java

package com.emahi.handler;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity {

private ProgressBar progress;
private TextView text;

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

progress = (ProgressBar) findViewById(R.id.progressBar1);
   text = (TextView) findViewById(R.id.textView1);
}

public void startProgress(View view) {
   // do something long
   Runnable runnable = new Runnable() {
     @Override
     public void run() {
       for (int i = 0; i <= 10; i++) {
         final int value = i;
          doFakeWork();
         progress.post(new Runnable() {
           @Override
           public void run() {
             text.setText("Updating");
             progress.setProgress(value);
           }
         });
       }
     }
   };
   new Thread(runnable).start();
 }

 // Simulating something timeconsuming
 private void doFakeWork() {
   try {
     Thread.sleep(2000);
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}


Output:


Saturday, February 15, 2014

Android ProgressBar.

activity_main.xml


<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="34dp"
        android:text="@string/b1" />

</RelativeLayout>


ActivityMain.java


package com.mahi.progressbar;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
Button b;  
ProgressDialog pb;  
private int progressBarStatus = 0;  
private Handler progressBarHandler = new Handler();  
private long fileSize = 0;

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

public void addListenerOnButtonClick() {  
         
       b = (Button) findViewById(R.id.button1);  
       b.setOnClickListener(new OnClickListener(){  
  
          @Override  
          public void onClick(View v) {
  
           // creating progress bar dialog  
           pb = new ProgressDialog(v.getContext());  
           pb.setCancelable(true);  
           pb.setMessage("File downloading ...");  
           pb.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
           pb.setProgress(0);  
           pb.setMax(100);  
           pb.show();  
  
           //reset progress bar and filesize status  
           progressBarStatus = 0;  
           fileSize = 0;  
  
           new Thread(new Runnable() {  
             public void run() {  
               while (progressBarStatus < 100) {  
  
                 // performing operation  
                 progressBarStatus = doOperation();  
  
                 try {  
                   Thread.sleep(1000);  
                 } catch (InterruptedException e) {  
                   e.printStackTrace();  
                 }  
  
                 // Updating the progress bar  
                 progressBarHandler.post(new Runnable() {  
                   public void run() {  
                     pb.setProgress(progressBarStatus);  
                   }  
                 });  
               }  
   
               if (progressBarStatus >= 100) {  
  
                   // sleeping for 1 second after operation completed  
                   try {  
                       Thread.sleep(1000);  
                   } catch (InterruptedException e) {e.printStackTrace();}  
    
                   pb.dismiss();  
               }  
             }  
            }).start();  
           }//end of onClick method  
         });  
        }  
  
   public int doOperation() {

       while (fileSize <= 10000) {  
           fileSize++;  
           if (fileSize == 1000) {  
               return 10;  
           }
           else if (fileSize == 2000) {  
               return 20;  
           }
           else if (fileSize == 3000) {  
               return 30;  
           }
           else if (fileSize == 4000) {  
            return 40;  
           }
           else if (fileSize == 5000) {  
               return 50;  
           }
           else if (fileSize == 6000) {  
               return 60;  
           }  
           else if (fileSize == 7000) {  
               return 70;  
           }  
           else if (fileSize == 8000) {  
               return 80;  
           }  
           else if (fileSize == 9000) {  
               return 90;  
           }  
           else if (fileSize == 10000) {  
               return 100;  
           }  
       }
       return 100;
   }
   
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Output:



Android AnalogClock and DigitalClock.

activity_main.xml

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

     <AnalogClock
        android:id="@+id/analogClock1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="22dp" />
 
    <DigitalClock
        android:id="@+id/digitalClock1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/analogClock1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="81dp" />

</RelativeLayout>


Output:


Android TimePicker

activity_main.xml


<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TimePicker
        android:id="@+id/timePicker1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="86dp" />
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/timePicker1"
        android:layout_alignParentTop="true"
        android:layout_marginTop="17dp"
        android:text="@string/current" />
 
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/timePicker1"
        android:layout_below="@+id/timePicker1"
        android:layout_marginLeft="37dp"
        android:layout_marginTop="55dp"
        android:text="@string/ct" />

</RelativeLayout>


MainActivity.java


package com.mahi.timepicker;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

public class MainActivity extends Activity {
TextView t1;
    TimePicker tp;
    Button b;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1=(TextView)findViewById(R.id.textView1);
        tp=(TimePicker)findViewById(R.id.timePicker1);
        b=(Button)findViewById(R.id.button1);
       
        tp.setIs24HourView(true); //code for 24 hour view
        
        t1.setText(getCurrentTime());  
        
        b.setOnClickListener(new OnClickListener(){  
            @Override  
            public void onClick(View v) {  
                 t1.setText(getCurrentTime());  
            }  
        });
}
public String getCurrentTime(){  
        String currentTime="Current Time: "+tp.getCurrentHour()+":"+tp.getCurrentMinute();  
        return currentTime;  
    }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}


Output:



Android DatePicker.

activity_main.xml


<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/btnChangeDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/cd" />

    <DatePicker
        android:id="@+id/dpResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="38dp" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/dpResult"
        android:layout_alignLeft="@+id/dpResult"
        android:layout_marginBottom="20dp"
        android:layout_marginLeft="20dp"
        android:text="@string/cd1" />

</RelativeLayout>


MainActivity.java


package com.mahi.datepicker;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class MainActivity extends Activity {
DatePicker dp;
    Button b;
    TextView textview1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview1=(TextView)findViewById(R.id.textView1);
        dp=(DatePicker)findViewById(R.id.dpResult);
        b=(Button)findViewById(R.id.btnChangeDate);
        
        textview1.setText(getCurrentDate());
        
        b.setOnClickListener(new OnClickListener(){
            @Override  
            public void onClick(View view) {
                textview1.setText(getCurrentDate());
            }
              
        });
}
public String getCurrentDate(){
        StringBuilder builder=new StringBuilder();
        builder.append("Current Date: ");
        builder.append((dp.getMonth() + 1)+"/");//month is 0 based
        builder.append(dp.getDayOfMonth()+"/");
        builder.append(dp.getYear());
        return builder.toString();
    }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}


Output:



Android RatingBar.

activity_main.xml


<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <RatingBar
        android:id="@+id/ratingBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="94dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/submit" />

</RelativeLayout>


MainActivity.java


package com.mahi.ratingbar;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.Toast;

public class MainActivity extends Activity {
RatingBar r;  
Button b;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButtonClick();
}
public void addListenerOnButtonClick(){  
        r=(RatingBar)findViewById(R.id.ratingBar1);  
        b=(Button)findViewById(R.id.button1);  
        //Performing action on Button Click  
        b.setOnClickListener(new OnClickListener(){  
  
            public void onClick(View v) {  
                //Getting the rating and displaying it on the toast  
                String rating=String.valueOf(r.getRating());  
                Toast.makeText(getApplicationContext(), rating, Toast.LENGTH_LONG).show();  
            }  
              
        });  
    }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Output:




AutoComplete in Android.

activity_main.xml


<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:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        android:text="@string/q" />

    <AutoCompleteTextView
        android:id="@+id/autoCompleteTextView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:layout_marginLeft="36dp"
        android:layout_marginTop="17dp"
        android:ems="10"
        android:text="">

        <requestFocus />
    </AutoCompleteTextView>
   
</RelativeLayout>

MainActivity.java


package com.mahi.autocomplete;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

public class MainActivity extends Activity {

String[] name ={"Mahi","Bipin","Sagar","Jignesh","Ashish","Satish","Dhananjay","Anil"};

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

ArrayAdapter<String> adapter = new ArrayAdapter<String>
         (this,android.R.layout.select_dialog_item,name);

AutoCompleteTextView actv= (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
         actv.setThreshold(1);
         actv.setAdapter(adapter);
         actv.setTextColor(Color.GREEN);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Output:



Android Spinner Example.

activity_main.xml


<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="14dp" />

</RelativeLayout>


MainActivity.java


package com.mahi.spinner;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener{

String[] students = {"Mahi", "Bipin", "Sagar", "Jignesh", "Ashish"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spin = (Spinner) findViewById(R.id.spinner1);  
        spin.setOnItemSelectedListener(this);
        
        ArrayAdapter<?> a = new ArrayAdapter(this,android.R.layout.simple_spinner_item,students);  
        a.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        
        spin.setAdapter(a);
}
@Override  
   public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {  
       Toast.makeText(getApplicationContext(),students[position] ,Toast.LENGTH_LONG).show();  
   }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}

Output:


AlertDialog Example in Android.

MainActitvity.java

package com.mahi.alertdialog;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;

public class MainActivity extends Activity {

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

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setMessage("Do you want to close this application ?")
        .setCancelable(false)
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            finish();
            }
        })
        .setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            //  Action for 'NO' Button
            dialog.cancel();
         }
        });

//Creating dialog box
        AlertDialog alert = builder.create();
        //Setting the title manually
        alert.setTitle("AlertDialogExample");
        alert.show();
        setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}


Output:

CkeckBox example in Android.

activity_main.xml


<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <CheckBox
        android:id="@+id/checkBox2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/checkBox1"
        android:layout_below="@+id/checkBox1"
        android:layout_marginTop="56dp"
        android:text="@string/cpp" />

    <CheckBox
        android:id="@+id/checkBox3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/checkBox2"
        android:layout_below="@+id/checkBox2"
        android:layout_marginTop="62dp"
        android:text="@string/j"
        android:checked="true" />

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="48dp"
        android:layout_marginTop="50dp"
        android:text="@string/c" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/checkBox2"
        android:layout_alignBottom="@+id/checkBox2"
        android:layout_toRightOf="@+id/checkBox1"
        android:text="@string/b1" />

</RelativeLayout>


MainActivity.java


package com.mahi.checkboxex;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

public class MainActivity extends Activity {

private CheckBox cpp,c,j;
private Button b;
   
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
c = (CheckBox) findViewById(R.id.checkBox1);
    cpp = (CheckBox) findViewById(R.id.checkBox2);
    j = (CheckBox) findViewById(R.id.checkBox3);
    b = (Button) findViewById(R.id.button1);
    
    b.setOnClickListener(new OnClickListener() {
     
           @Override
           public void onClick(View v) {
 
               // Create string buffer to
 
               StringBuffer OUTPUT = new StringBuffer();
               OUTPUT.append("C Language : ")
                       .append(c.isChecked());
 
               OUTPUT.append("\nC++ : ").append(
                       cpp.isChecked());
 
              OUTPUT.append("\nJava :").append(
                       j.isChecked());
 
               Toast.makeText(MainActivity.this, OUTPUT.toString(),
                       Toast.LENGTH_LONG).show();
 
           }
       });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Output: