Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Sunday, September 22, 2013

ToggleButton in Android

ToggleButton allows to select either states of the action. See below code.

activity_practice.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"
android:background="#d0d0d0"
    tools:context=".PracticeActivity" >

    <ToggleButton 
        android:id="@+id/toggle1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        />

    <ToggleButton 
        android:id="@+id/toggle2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn="Turn On"
        android:textOff="Turn Off"
        android:layout_margin="20dp"
        />
    
    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn1"
        android:layout_margin="20dp"
        />
</LinearLayout>

PracticeActivity.java

package com.agilissystems.practicework;

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.Toast;
import android.widget.ToggleButton;

public class PracticeActivity extends Activity implements OnClickListener {

ToggleButton oToggleB1, oToggleB2 ;
Button oBtn1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_practice);
        oToggleB1 = (ToggleButton) findViewById(R.id.toggle1);
        oToggleB2 = (ToggleButton) findViewById(R.id.toggle2);
        
        oBtn1 = (Button) findViewById(R.id.btn1);
        oBtn1.setOnClickListener(this);
    }


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


@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (arg0.getId() == R.id.btn1){
StringBuffer oStr1 = new StringBuffer();
oStr1.append("\nToggle 1 : " + oToggleB1.getText().toString());
oStr1.append("\nToggle 2 : "+ oToggleB2.getText().toString());
Toast.makeText(this, "State : " + oStr1.toString(), Toast.LENGTH_LONG).show();
}
}

    
}


Strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Practicework</string>
    <string name="action_settings">Settings</string>
<string name="btn1">Check Status</string>

</resources>

When we add toggle button in the code, it will give ON of OFF state by default which you can see in the first toggle button. But in most of the cases, we need to display different text for ON or OFF state, which we can achieve through textOn and textOff attributes of ToggleButton which are highlighted in above code. getText() method will return the current state of ToggleButton.


Difference Between Margin and Padding attributes

Let's start with example.

activity_practice.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"
android:background="#d0d0d0"
    tools:context=".PracticeActivity" >

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


</LinearLayout>

PracticeActivity.java

package com.agilissystems.practicework;

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.Toast;

public class PracticeActivity extends Activity implements OnClickListener {

private Button oBtn1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_practice);
        
        oBtn1 = (Button) findViewById(R.id.btn1);

        oBtn1.setOnClickListener(this);

    }


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


@Override
public void onClick(View v) {
// TODO Auto-generated method stub

switch (v.getId())
{
case R.id.btn1:
Toast.makeText(this, "You clicked on Button 1 !!!", Toast.LENGTH_LONG).show();
break;


}
}
    

}

Strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Practicework</string>
    <string name="action_settings">Settings</string>
<string name="btn1">Button 1</string>

</resources>

When you run the above application will place the button element at left top corner of the screen. Margin attribute allows spacing surrounding the element. Add below line to button element of activity_practice.xml file.

android:layout_margin="20dp"

will add 20dp spacing surrounding the button element. but if you want to apply the spacing to specific side(s) then there are attributes called layout_margintop, layout_marginbottom, layout_marginleft and layout_marginright.

Now, we need to apply spacing surrounding the text of the button then there is attribute called "padding", add below line to button element.

android:padding="40dp"

It will add 40dp spacing to all side of text inside the button. there are other attributes like paddingLeft, paddingRight, paddingTop, paddingBottom, paddingStart, paddingEnd which will add spacing to specif side of the text.

Hope, now you are clear about the difference between margin and padding attributes.




 

Difference between Gravity and Layout_Gravity

Many android developers are asking me the difference between the properties like Gravity and Layout_Gravity. Below example will explain the differences.

In simple term, Gravity is related to position of the content of the view whereas Layout_gravity is related to the position of the view in its parent element.

You can easily observe that if you want to check the usage of Layout_gravity then you need to make sure that respective view width should be smaller than width of parent element. (check Btn1 attributes).

As i mentioned, Gravity is applied to content of the view. check the attributes of Btn2. Gravity attribute allows to align the text of the button within the button area. But ensure that the width of the view should be wider than text.



activity_practice.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"

    tools:context=".PracticeActivity" >

<Button 
   android:id="@+id/btn1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@string/btn1"
   android:layout_margin="40dp"
   android:layout_gravity="right"
   android:padding="20dp"
   />

<Button 
   android:id="@+id/btn2"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:text="@string/btn2"
   android:layout_margin="40dp"
   android:gravity="right"
   android:padding="20dp"
   />
</LinearLayout>


PracticeActivity.java

package com.agilissystems.practicework;

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.Toast;

public class PracticeActivity extends Activity implements OnClickListener {

private Button oBtn1, oBtn2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_practice);
        
        oBtn1 = (Button) findViewById(R.id.btn1);
        oBtn2 = (Button) findViewById(R.id.btn2);
        oBtn1.setOnClickListener(this);
        oBtn2.setOnClickListener(this);
    }


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


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId())
{
case R.id.btn1:
Toast.makeText(this, "You clicked on Button 1 !!!", Toast.LENGTH_LONG).show();
break;
case R.id.btn2:
Toast.makeText(this, "You clicked on Button 2 !!!", Toast.LENGTH_LONG).show();
break;
}
}
    
}


Strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Practicework</string>
    <string name="action_settings">Settings</string>
<string name="btn1">Button 1</string>
<string name="btn2">Button 2</string>
</resources>


Monday, September 10, 2012

Android | TabView

Below is source code of how to implement TabView in Android.

Note: It has been verified in Android emulator 4.0.3.

activity_tab_example.xml


<TabHost 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:id="@android:id/tabhost" >
   
    <LinearLayout
        android:id="@+id/tablinearlayout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">
       
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </TabWidget>

       
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            ></FrameLayout>
    </LinearLayout>


   
</TabHost>

strings.xml

<resources>

    <string name="app_name">TabExample</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_tab_example">Tab Example</string>
    <string name="title_activity_plus_tab">PlusTabActivity</string>
    <string name="title_activity_minus_tab">MinusTabActivity</string>
    <string name="title_activity_multiplication_tab">MultiplicationTabActivity</string>
    <string name="title_activity_division_tab">DivisionTabActivity</string>
    <string name="plus">You clicked on Plus.</string>
    <string name="minus">You clicked on Minus.</string>
    <string name="division">You clicked on Division.</string>
    <string name="multiplication">You clicked on Multiplication.</string>

</resources>

TabExample.java

package com.example.tabexample;

import android.os.Bundle;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.util.Log;
import android.view.Menu;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

@SuppressWarnings("deprecation")
public class TabExample extends TabActivity {

private TabHost oTabHost;
    @SuppressWarnings("null")
@Override
    public void onCreate(Bundle savedInstanceState) {
        
    try
    {
    super.onCreate(savedInstanceState);
       
      
       setContentView(R.layout.activity_tab_example);
       
       oTabHost = (TabHost) findViewById(android.R.id.tabhost);
       
       oTabHost = getTabHost();
       
       TabHost.TabSpec oTabSpec1 ;
       oTabSpec1 = oTabHost.newTabSpec("+");
       oTabSpec1.setIndicator("+", getResources().getDrawable(R.drawable.sq_plus));
       Intent oPlusIntent = new Intent(this, PlusTabActivity.class);
       oTabSpec1.setContent(oPlusIntent);
       oTabHost.addTab(oTabSpec1);
       
       TabHost.TabSpec oTabSpec2 = oTabHost.newTabSpec("-");
       oTabSpec2.setIndicator("-", getResources().getDrawable(R.drawable.sq_minus));        
       Intent oMinusIntent = new Intent(this, MinusTabActivity.class);
       oTabSpec2.setContent(oMinusIntent);
       oTabHost.addTab(oTabSpec2);
       
       TabHost.TabSpec oTabSpec3 = oTabHost.newTabSpec("*");
       oTabSpec3.setIndicator("*", getResources().getDrawable(R.drawable.multiply));        
       Intent oMultiplicationIntent = new Intent(this, MultiplicationTabActivity.class);
       oTabSpec3.setContent(oMultiplicationIntent);
       oTabHost.addTab(oTabSpec3);
       
       TabHost.TabSpec oTabSpec4 = oTabHost.newTabSpec("/");
       oTabSpec4.setIndicator("/", getResources().getDrawable(R.drawable.sign_direction));
       Intent oDivisionIntent = new Intent(this, DivisionTabActivity.class);
       oTabSpec4.setContent(oDivisionIntent);
       oTabHost.addTab(oTabSpec4);
    }
    catch(Exception e){
    Log.d("TabExample", e.getMessage());
    }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_tab_example, menu);
        return true;
    }
}


Snapshot of application structure. I have added 4 layout files and 4 images files in drawable folder.





Result:

In below example, you will get only text in each tab. if you want images then you need to keep first parameter of setIndicator method of each tab blank.


Tuesday, September 4, 2012

Android | DialogBox Example

Here, i would like to show you how we can show confirmation dialog box.

Note: below code has been verified on Android Emulator 4.0.3.

Code: activity_dialog_example.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" >


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

    <Button
        android:id="@+id/btnitems"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/btnitems"/>
 
    <Button
        android:id="@+id/btnsingleitem"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/btnsingleitem"/>
     
</LinearLayout>


Code: strings.xml


<resources>

    <string name="app_name">DialogExample</string>

    <string name="menu_settings">Settings</string>
    <string name="title_activity_dialog_example">Dialog Example</string>

    <string name="btnyesno">Yes or No</string>
    <string name="deletedialog">Confirmation</string>
    <string name="deletemessage">Are you sure, Do you want to exit ?</string>
 
    <string name="btnitems">Items</string>
    <string name="btnsingleitem">Single Item Selection</string>
</resources>

Code:DialogExample.java


package com.example.dialogexample;

import javax.crypto.spec.OAEPParameterSpec;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;



public class DialogExample extends Activity implements OnClickListener {

static final int YESORNO_DIALOG = 1;
static final int IITEMS_DIALOG = 2;
static final int SINGLEITEMSELECTION_DIALOG = 3;

Button btnYesNo, btnItems, btnSingleItem;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dialog_example);
     
        btnYesNo = (Button) findViewById(R.id.btnyesno);
        btnYesNo.setOnClickListener(this);
     
        btnItems = (Button) findViewById(R.id.btnitems);
        btnItems.setOnClickListener(this);
     
        btnSingleItem = (Button) findViewById(R.id.btnsingleitem);
        btnSingleItem.setOnClickListener(this);
     
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_dialog_example, menu);
        return true;
    }

    @Override
    @Deprecated
    protected Dialog onCreateDialog(int id) {
    // TODO Auto-generated method stub
AlertDialog.Builder oAlert = new Builder(this);     //Here "this" is must if we use "getApplicationContext" then shows an error.
AlertDialog oDialog = (AlertDialog)  super.onCreateDialog(id);

    try
    {

    switch (id){
    case DialogExample.YESORNO_DIALOG:

    oAlert.setMessage(R.string.deletemessage);
    oAlert.setTitle(R.string.deletedialog);
    oAlert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
   
    public void onClick(DialogInterface arg0, int arg1) {
    // TODO Auto-generated method stub
    DialogExample.this.finish();
    }
    });
   
    oAlert.setNegativeButton("No", new DialogInterface.OnClickListener() {
   
    public void onClick(DialogInterface arg0, int arg1) {
    // TODO Auto-generated method stub
    arg0.cancel();
    }
    });
   
    oDialog = oAlert.create();
    break;
    case IITEMS_DIALOG:
final String[] strColor = {"Red","Green","Blue"};
oAlert.setTitle("Colors");

oAlert.setItems(strColor, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), strColor[arg1].toString(), Toast.LENGTH_LONG).show();
}
});
oDialog = oAlert.create();
break;

    case SINGLEITEMSELECTION_DIALOG:
    final String[] strFruit = {"Apple","Grapes","Mango"};
    oAlert.setTitle("Fruits");
    oAlert.setSingleChoiceItems(strFruit, -1, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), strFruit[arg1].toString(), Toast.LENGTH_LONG).show();

}
});
    oDialog = oAlert.create();
    break;
    }

   }
    catch(Exception e){
    Log.d("Dialogbox",e.getMessage().toString());
   
    }
    return oDialog;
    }

public void onClick(View arg0) {
// TODO Auto-generated method stub
try{

switch(arg0.getId()){
case R.id.btnyesno:
showDialog(YESORNO_DIALOG);
break;
case R.id.btnitems:
showDialog(IITEMS_DIALOG);
break;
case R.id.btnsingleitem:
showDialog(SINGLEITEMSELECTION_DIALOG);
break;

}
}
catch(Exception e){
Log.d("Dialogbox",e.getMessage().toString());
}
}
}



Result of Clicking on "Yes or No" button :




Note: 
As per the code, when user selects "Yes" then application will be closed and nothing will happen when user selects "No".
Result of while user clicks on "Items" button


Result of while user clicks on "Select Single item".






Tuesday, August 28, 2012

Android | RatingBar Example

Below is an example of Android RatingBar element.

Note: Example is verified with Android 4.0.3 emulator.

activity_rating_bar_example.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" >

   
    <RatingBar
        android:id="@+id/rbrating"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="5"
        android:rating="0"
        android:stepSize=".1"
       />
   
    <TextView
        android:id="@+id/tvratingvalue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tvratingvalue"
/>
    <TextView
        android:id="@+id/tvuser"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tvuser"
/>  

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


strings.xml

<resources>

    <string name="app_name">RatingBarExample</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_rating_bar_example">RatingBar Example</string>
    
    <string name="tvratingvalue"></string>
    <string name="tvuser"></string>
    <string name="btnok">Set rating at 2.5</string>
</resources>

RatingBarExample.java

package com.example.ratingbarexample;

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.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;

public class RatingBarExample extends Activity implements OnRatingBarChangeListener, OnClickListener {
private RatingBar rbRatingBar  ;
private TextView tvRatingValue, tvUser;
private Button btnOk;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rating_bar_example);
        
        rbRatingBar = (RatingBar) findViewById(R.id.rbrating);
        tvRatingValue = (TextView) findViewById(R.id.tvratingvalue);
        tvUser = (TextView) findViewById(R.id.tvuser);
        btnOk  = (Button) findViewById(R.id.btnok);
        
        rbRatingBar.setOnRatingBarChangeListener(this);
        btnOk.setOnClickListener(this);
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_rating_bar_example, menu);
        return true;
    }

public void onRatingChanged(RatingBar arg0, float arg1, boolean arg2) {
// TODO Auto-generated method stub
tvRatingValue.setText("Rating : " + String.valueOf(arg1));
if (arg2 == true)
tvUser.setText("Changed by User"); //shows when user do by himself/herself
else
tvUser.setText("Changed by function"); // when set by function like clicking on Button
}

public void onClick(View arg0) {
// TODO Auto-generated method stub
rbRatingBar.setProgress(25);
}
}

Result:


Android | ImageView Example

Imageview used to display image.

Note: Below code is verified with Android 4.0.3 emulator.

activity_image_view_example.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" >

    <ImageView
        android:id="@+id/ivfirst"
        android:layout_height="match_parent"
        android:layout_width ="match_parent"
        android:src="@drawable/ic_launcher"
        android:contentDescription="@string/ivfirst"
        />
</LinearLayout>

strings.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" >

    <ImageView
        android:id="@+id/ivfirst"
        android:layout_height="match_parent"
        android:layout_width ="match_parent"
        android:src="@drawable/ic_launcher"
        android:contentDescription="@string/ivfirst"
        />
</LinearLayout>

ImageViewExample.java


package com.example.testexample;

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

public class ImageViewExample extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_view_example);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_image_view_example, menu);
        return true;
    }
}


Result:




Android | Spinner Example

When we have multiple values and out of them we need to select one item then we can use Spinner UI component.

Populating Spinner is little bit different. I would like to guide you that there are two sources from which we can populate spinner (1) Array and (2) database.

Adapter is playing key role between UI component and data sources.

Note: below example verified on Android 4.0.3 emulator.

activity_spinner_example.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" >
   
    <Spinner
        android:id="@+id/spnrcountries"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />


</LinearLayout>


Strings.xml


<resources>

    <string name="app_name">SpinnerExample</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_spinner_example">Spinner Example</string>
   
   
</resources>

SpinnerExample.java



package com.example.spinnerexample;

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

public class SpinnerExample extends Activity  {

private Spinner spnrCountries;
private String[] strCountries = {"US","UK","Spain","Germany","Italy","India","China"};

private ArrayAdapter<String> oArrayAdapter ;

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner_example);
       

        spnrCountries = (Spinner) findViewById(R.id.spnrcountries);
       

        oArrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, strCountries);
        spnrCountries.setAdapter(oArrayAdapter);
       
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_spinner_example, menu);
        return true;
    }


}


Result:




Android | Toast Example

In most of the applications, we need to show messages like "Data save successfully.", "Delete successfully.". To show such type of message, android provides "Toast" feature.

Note: verified on Android 4.0.3 Emulator.


Below code will help you get above toast message.

Code of Layout file:


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

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

Code of Strings.xml file:


<resources>

    <string name="app_name">ToastExample</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_toast_example">Toast Example</string>

    <string name="btnok">OK</string>
</resources>



Code of Java file:


package com.example.toastexample;

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.Toast;

public class ToastExample extends Activity implements OnClickListener {

private Button btnOk;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_toast_example);
       
        btnOk = (Button) findViewById(R.id.btnok);
       
        btnOk.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_toast_example, menu);
        return true;
    }

public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Hi Friends !!" , Toast.LENGTH_LONG).show();

}
}


Above, code always displays message at default location. Now, if you want to set toast at your desired location (like center of screen) then replace above "OnClick" method with below one in "Java" file.

public void onClick(View arg0) {
// TODO Auto-generated method stub
try{
Toast oToast = Toast.makeText(getApplicationContext(), "Hi Friends!!", Toast.LENGTH_LONG);
oToast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
oToast.show();
}
catch(Exception e){
Log.e("Toast App", e.getMessage());
}
} 


Result:


Now, it is time to design own screen for Toast.

activity_toast_example.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" >

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

toast_layout.xml (Create this file in layout folder and add an image in each drawable folder)

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/tbllayouttoast"
    android:background="#bbff0000"
     >
    <TableRow>
        <ImageView 
            android:id="@+id/ivimage"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/us"
            android:contentDescription="@string/ivimage"
            android:padding="10dp"
            />
        <TextView
            android:id="@+id/tvimage"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="@string/tvimage"
            android:padding="10dp"
            android:textColor="#FFFFFFFF"
            />
    </TableRow>
</TableLayout>

Strings.xml

<resources>

    <string name="app_name">ToastExample</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_toast_example">Toast Example</string>

    <string name="btnok">OK</string>
    <string name="ivimage"></string>
    <string name="tvimage">Hi Friends !!</string>
</resources>

ToastExample.java

package com.example.toastexample;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

public class ToastExample extends Activity implements OnClickListener {
private Button btnOk;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_toast_example);
        
        btnOk = (Button) findViewById(R.id.btnok);
        
        btnOk.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_toast_example, menu);
        return true;
    }

public void onClick(View arg0) {
// TODO Auto-generated method stub
try{
LayoutInflater oLayoutInflater = getLayoutInflater();
View oView = oLayoutInflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.tbllayouttoast));
Toast oToast = new Toast(getApplicationContext());
oToast.setDuration(Toast.LENGTH_LONG);
oToast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
oToast.setView(oView);
oToast.show();

}
catch(Exception e){
Log.e("Toast App", e.getMessage());
}
}

}


Result: