Thursday, February 26, 2015

How to change position of Toast in android ?

How to change position of Toast in android ?

What is Toast?

A toast provides simple feedback about an operation as a simple popup message. It is usually be displayed at the bottom of the Application.

What are we going to develop?

The application which we are going to develop will help you to create toast messages in different positions by altering Gravity and also by taking custom X-offset and Y-offset values.

hirpara

Positioning the Toast message

A standard toast notification appears at the bottom of the screen, centered horizontally. You can alter this position with the help of setGravity(int, int, int) method. This method accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset.
Below piece of code will display the Toast at top-left corner with X-Offset and Y-Offset as 100 and 200 respectively.


  1. Toast toast = Toast.makeText(getApplicationContext(), "Hello toast!", Toast.LENGTH_SHORT);
  2. // Set the Gravity to Top and Left
  3. toast.setGravity(Gravity.TOP | Gravity.LEFT, 100, 200);
  4. toast.show();

To show the Toast in Top Right corner with X-Offset and Y-Offset as 100 and 200 respectively:

1
2
3
4
Toast toast = Toast.makeText(getApplicationContext(), "Hello toast!", Toast.LENGTH_SHORT);
// Set the Gravity to Top and Right
toast.setGravity(Gravity.TOP | Gravity.RIGHT, 100, 200);
toast.show();



Step 1: Create Android Application Project

  • Create new android project [File >> New >> Android Application Project] with project name AndroidToastPosition
  • Enter package name as ‘com.prgguru.example’ and activity name as ‘MainActivity’
  • Choose Minimum Required SDK, Target SDK and Compile with (Choose latest SDKs to make sure Facebook SDK will work without a ny issues). Confused on choosing these options? Take a look at Minimum Required SDK – Target SDK – Compile With post.
  • Click Next button and finally click ‘Finish’ to create project
Step 2: Design screen
Open activity_main.xml and replace it with below code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<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="com.prgguru.example.MainActivity" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="X-Offset" />
    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:gravity="center"
        android:inputType="number" >
        <requestFocus />
    </EditText>
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:text="Y-Offset" />
    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView2"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:gravity="center"
        android:inputType="number" >
    </EditText>
    <Button
        android:id="@+id/button1"
        android:layout_width="500dp"
        android:layout_height="60dp"
        android:layout_below="@+id/editText2"
        android:layout_centerHorizontal="true"
        android:onClick="showToastTopLeft"
        android:text="Show Toast (With Top/Left Gravity)" >
    </Button>
    <Button
        android:id="@+id/button2"
        android:layout_width="500dp"
        android:layout_height="60dp"
        android:layout_below="@+id/button1"
        android:layout_centerHorizontal="true"
        android:onClick="showToastTopRight"
        android:text="Show Toast (With Top/Right Gravity)" >
    </Button>
    <Button
        android:id="@+id/button3"
        android:layout_width="500dp"
        android:layout_height="60dp"
        android:layout_below="@+id/button2"
        android:layout_centerHorizontal="true"
        android:onClick="showToastBottomLeft"
        android:text="Show Toast (With Bottom/Left Gravity)" >
    </Button>
    <Button
        android:id="@+id/button4"
        android:layout_width="500dp"
        android:layout_height="60dp"
        android:layout_below="@+id/button3"
        android:layout_centerHorizontal="true"
        android:onClick="showToastBottomRight"
        android:text="Show Toast (With Bottom/Right Gravity)" >
    </Button>
</RelativeLayout>
Step 3: MainActivity.java – Main Class
Open MainActivity.java and replace it with below code.
Each line of code is commented well, if you still have any doubt or question 0 Comments it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package com.prgguru.example;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
     
    /**
     * When Button "@+id/button1" is clicked
     * @param v
     */
    public void showToastTopLeft(View v) {
        EditText e1 = (EditText) findViewById(R.id.editText1);
        EditText e2 = (EditText) findViewById(R.id.editText2);
        if (e1.getText().toString().trim().length() > 0
                && e2.getText().toString().trim().length() > 0) {
            String editText1 = e1.getText().toString();
            String editText2 = e2.getText().toString();
            int xOffset = Integer.parseInt(editText1);
            int yOffset = Integer.parseInt(editText2);
            Toast toast = Toast.makeText(getApplicationContext(), "Hello toast!", Toast.LENGTH_SHORT);
            // Set the Gravity to Top and Left
            toast.setGravity(Gravity.TOP | Gravity.LEFT, xOffset, yOffset);
            toast.show();
        } else {
            Toast.makeText(getApplicationContext(),
                    "Please enter value for X-Offset and/or Y-Offset", Toast.LENGTH_SHORT)
                    .show();
        }
    }
     
    /**
     * When Button "@+id/button2" is clicked
     * @param v
     */
    public void showToastTopRight(View v) {
        EditText e1 = (EditText) findViewById(R.id.editText1);
        EditText e2 = (EditText) findViewById(R.id.editText2);
        if (e1.getText().toString().trim().length() > 0
                && e2.getText().toString().trim().length() > 0) {
            String editText1 = e1.getText().toString();
            String editText2 = e2.getText().toString();
            int xOffset = Integer.parseInt(editText1);
            int yOffset = Integer.parseInt(editText2);
            Toast toast = Toast.makeText(getApplicationContext(), "Hello toast!", Toast.LENGTH_SHORT);
            // Set the Gravity to Top and Right
            toast.setGravity(Gravity.TOP | Gravity.RIGHT, xOffset, yOffset);
            toast.show();
        } else {
            Toast.makeText(getApplicationContext(),
                    "Please enter value for X-Offset and/or Y-Offset", Toast.LENGTH_SHORT)
                    .show();
        }
    }
     
    /**
     * When Button "@+id/button3" is clicked
     * @param v
     */
    public void showToastBottomLeft(View v) {
        EditText e1 = (EditText) findViewById(R.id.editText1);
        EditText e2 = (EditText) findViewById(R.id.editText2);
        if (e1.getText().toString().trim().length() > 0
                && e2.getText().toString().trim().length() > 0) {
            String editText1 = e1.getText().toString();
            String editText2 = e2.getText().toString();
            int xOffset = Integer.parseInt(editText1);
            int yOffset = Integer.parseInt(editText2);
            Toast toast = Toast.makeText(getApplicationContext(), "Hello toast!", Toast.LENGTH_SHORT);
            // Set the Gravity to Bottom and Left
            toast.setGravity(Gravity.BOTTOM | Gravity.LEFT, xOffset, yOffset);
            toast.show();
        } else {
            Toast.makeText(getApplicationContext(),
                    "Please enter value for X-Offset and/or Y-Offset", Toast.LENGTH_SHORT)
                    .show();
        }
    }
     
    /**
     * When Button "@+id/button4" is clicked
     * @param v
     */
    public void showToastBottomRight(View v) {
        EditText e1 = (EditText) findViewById(R.id.editText1);
        EditText e2 = (EditText) findViewById(R.id.editText2);
        if (e1.getText().toString().trim().length() > 0
                && e2.getText().toString().trim().length() > 0) {
            String editText1 = e1.getText().toString();
            String editText2 = e2.getText().toString();
            int xOffset = Integer.parseInt(editText1);
            int yOffset = Integer.parseInt(editText2);
            Toast toast = Toast.makeText(getApplicationContext(), "Hello toast!", Toast.LENGTH_SHORT);
            // Set the Gravity to Bottom and Right
            toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT, xOffset, yOffset);
            toast.show();
        } else {
            Toast.makeText(getApplicationContext(),    "Please enter value for X-Offset and/or Y-Offset", Toast.LENGTH_SHORT).show();
        }
    }
}

Demo

That’s all. It’s time to test our code.
Run the application using emulator or device by right clicking on the project >> Run as >> Android applicaiton >> Choose emulator or device.




Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project (How to import android project in eclipse).
Download Source Code

Android Audio Manager New Tutorial

in  post, I will be discussing about using , AudioManager Class in Android applications.

with AudioManager Class provides access to volume and ringer mode control which was added in API level
I wrote separate post about using AudioManager in getting and setting the current device’s volume (Media player, , Notification etc) long back.

But in this post, I am going to discuss about using AudioManager in getting and setting the ringer mode (Silent, Vibrate and Normal).
What is Seekbar?
A SeekBar is an extension of ProgressBar that adds a draggable thumb. The user can touch the thumb and drag left or right to set the current progress level or use the arrow keys.
Usage: Seekbar can be used to adjust media player volume, set brightness of the screen, seek a playing music etc.
What are we going to develop?
We will develop a simple application to demonstrate how it is used to set Media player, Ringer, Alarm and Notification volume for your device.


Quick Links.

  • Project Structure
  • Code Listings
  • Demo
  • Download Source Code

Project .Structure

Layout creation:
  • Create new android project [File >> New >> Android Project] with project name SeekBarExample
  • Click next and select target android device version [I chose version 2.2]
  • Click next and enter package name – ‘com.prgguru.android’
  • Click finish

Code Listings

Layout XML:
Open main.xml present under /res/layout folder and replace the XML with the below one.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?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" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Adjust Media player volume"
        android:textAppearance="?android:attr/textAppearanceLarge" android:padding="10px"/>
    <SeekBar
        android:id="@+id/seekBar1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Adjust Ringer volume"
        android:textAppearance="?android:attr/textAppearanceLarge" android:padding="10px" />
    <SeekBar
        android:id="@+id/seekBar2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />   
    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Adjust Alarm volume"
        android:textAppearance="?android:attr/textAppearanceLarge" android:padding="10px"/>
    <SeekBar
        android:id="@+id/seekBar3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Adjust Notification volume"
        android:textAppearance="?android:attr/textAppearanceLarge" android:padding="10px"/>
    <SeekBar
        android:id="@+id/seekBar4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>
Application layout will look like:
Change to graphical layout of Main.xml, the layout design should look like below:

Create following objects under SeekBarExampleActivity class to refer seekbars and to get audimanager:
1
2
3
4
5
private SeekBar mediaVlmSeekBar = null;
private SeekBar ringerVlmSeekBar = null;
private SeekBar alarmVlmSeekBar = null;
private SeekBar notifyVlmSeekBar = null;
private AudioManager audioManager = null;
Suggests an audio stream whose volume should be changed by the hardware volume controls. Add following snippet inside onCreate method after ‘super.onCreate(savedInstanceState)’
1
2
3
4
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);       
this.setVolumeControlStream(AudioManager.STREAM_RING);   
this.setVolumeControlStream(AudioManager.STREAM_ALARM);
this.setVolumeControlStream(AudioManager.STREAM_NOTIFICATION);
A separate method ‘initControls’ to handle the seekbars is going to be created, call it inside onCreate method:

1
initControls();
private void initControls() {
//Return the handle to a system-level service - 'AUDIO'.
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//Find the seekbar 1
mediaVlmSeekBar = (SeekBar) findViewById(R.id.seekBar1);
//Set the max range(Volume in this case) of seekbar
//for Media player volume
mediaVlmSeekBar.setMax(audioManager
        .getStreamMaxVolume(AudioManager.STREAM_MUSIC));
//Set the progress with current Media Volume
mediaVlmSeekBar.setProgress(audioManager
        .getStreamVolume(AudioManager.STREAM_MUSIC));
//Find the seekbar 2
ringerVlmSeekBar = (SeekBar) findViewById(R.id.seekBar2);
//Set the max range(Volume in this case) of seekbar
//for Phone ringer volume
ringerVlmSeekBar.setMax(audioManager
        .getStreamMaxVolume(AudioManager.STREAM_RING));
//Set the progress with current Ringer Volume
ringerVlmSeekBar.setProgress(audioManager
        .getStreamVolume(AudioManager.STREAM_RING));
//Find the seekbar 3
alarmVlmSeekBar = (SeekBar) findViewById(R.id.seekBar3);
//Set the max range(Volume in this case) of seekbar
//for Alarm volume
alarmVlmSeekBar.setMax(audioManager
        .getStreamMaxVolume(AudioManager.STREAM_ALARM));
//Set the progress with current Alarm Volume
alarmVlmSeekBar.setProgress(audioManager
        .getStreamVolume(AudioManager.STREAM_ALARM));
//Find the seekbar 4
notifyVlmSeekBar = (SeekBar) findViewById(R.id.seekBar4);
//Set the max range(Volume in this case) of seekbar
//for Notification volume
notifyVlmSeekBar.setMax(audioManager
        .getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION));
//Set the progress with current Notification Volume
notifyVlmSeekBar.setProgress(audioManager
        .getStreamVolume(AudioManager.STREAM_NOTIFICATION));
try {
    //Listener to receive changes to the SeekBar1's progress level
    mediaVlmSeekBar
        .setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
    public void onStopTrackingTouch(SeekBar arg0) {
        }
    public void onStartTrackingTouch(SeekBar arg0) {
        }
    //When progress level of seekbar1 is changed
    public void onProgressChanged(SeekBar arg0,
        int progress, boolean arg2) {
    audioManager.setStreamVolume(
        AudioManager.STREAM_MUSIC, progress, 0);
    }
 });
   //Listener to receive changes to the SeekBar2's progress level
   ringerVlmSeekBar
         .setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
   public void onStopTrackingTouch(SeekBar arg0) {
        }
   public void onStartTrackingTouch(SeekBar arg0) {
        }
   //When progress level of seekbar2 is changed
   public void onProgressChanged(SeekBar arg0,
        int progress, boolean arg2) {
    audioManager.setStreamVolume(
        AudioManager.STREAM_RING, progress, 0);
     }
 });
   //Listener to receive changes to the SeekBar3's progress level
   alarmVlmSeekBar
        .setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
   public void onStopTrackingTouch(SeekBar arg0) {
        }
   public void onStartTrackingTouch(SeekBar arg0) {
        }
   //When progress level of seekbar3 is changed
   public void onProgressChanged(SeekBar arg0,
        int progress, boolean arg2) {
     audioManager.setStreamVolume(
            AudioManager.STREAM_ALARM, progress, 0);
    }
 });
   //Listener to receive changes to the SeekBar4's progress level
   notifyVlmSeekBar
        .setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
   public void onStopTrackingTouch(SeekBar arg0) {
        }
   public void onStartTrackingTouch(SeekBar arg0) {
        }
   //When progress level of seekbar4 is changed
   public void onProgressChanged(SeekBar arg0,
            int progress, boolean arg2) {
     audioManager.setStreamVolume(
        AudioManager.STREAM_NOTIFICATION, progress,0);
    }
 });
} catch (Exception e) {
    e.printStackTrace();
}
}


Demo

Let us test the application:
Run click on the project >> Run as >> Android application
You could see following screen:

Blog Archive

increase adsense earning

Package
URL OR WEB ADDRESH

Live Traffic Feed