Pages

Tuesday 29 October 2013

Screenshot Using DDMS on Windows(Android Device)


What is DDMS?

Android provides a debugging tool called the Dalvik Debug Monitor Server (DDMS). 

Advantages of DDMS:

   1 . DDMS provides port-forwarding services.
    2 . Screen capture on the device.
    3 . Thread and heap information on the device.
    4 . Logcat.
    5 . Process.
    6 . Radio state information.
    7  . Incoming call and SMS spoofing, location data spoofing, and more.

Screen Shot

1. First Create AVD, open   Emulator .
2open DDMS Prospective ,DDMS Windows With the List of Devices Connected to it.




3  Finally Click on Save Button.



Saturday 26 October 2013

Handler and AsyncTask in Android


Android Handler

  1. Handler allows to add messages to the thread which creates it and It also enables you to schedule some runnable to execute at some time in future.
  2. The Handler is associated with the application’s main thread. It handles and schedules messages and runnables sent from background threads to the app main thread.
  3. If you are doing multiple repeated tasks, for example downloading multiple images which are to be displayed in ImageViews (like downloading thumbnails) upon download, use a task queue with Handler.
  4. There are two main uses for a Handler. First is to schedule messages and runnables to be executed as some point in the future; and second Is to enqueue an action to be performed on a different thread than your own.
  5. Scheduling messages is accomplished with the the methods like post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long), sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long), and sendMessageDelayed(Message, long) methods.
  6. When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, broadcast receivers, etc) and any windows they create.
  7. You can create your own threads, and communicate back with the main application thread through a Handler.

Android AsynkTask

  1. Async task enables you to implement MultiThreading without get Hands dirty into threads. AsyncTask enables proper and easy use of the UI thread. It allows performing background operations and passing the results on the UI thread.
  2. If you are doing something isolated related to UI, for example downloading data to present in a list, go ahead and use AsyncTask.
  3. AsyncTasks should ideally be used for short operations (a few seconds at the most.)
  4. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
  5. In onPreExecute you can define code, which need to be executed before background processing starts.
  6. doInBackground have code which needs to be executed in background, here in doInBackground we can send results to multiple times to event thread by publishProgress() method, to notify background processing has been completed we can return results simply.
  7. onProgressUpdate() method receives progress updates from doInBackground method, which is published via publishProgress method, and this method can use this progress update to update event thread
  8. onPostExecute() method handles results returned by doInBackground method.
  9. The generic types used are
    • Params, the type of the parameters sent to the task upon execution
    • Progress, the type of the progress units published during the background computation.
    • Result, the type of the result of the background computation.
  10. If an async task not using any types, then it can be marked as Void type.
  11. An running async task can be cancelled by calling cancel(boolean) method.

Friday 25 October 2013

AsyncroTask Example To Get Server Data


AsyncroTask Basics:

     1.  AsyncTask provide easy way to use of the UI thread.
 
     2.  Perform background operations and publish results on the UI thread without having to     manipulate             threads and/or handlers.

     3.  AsyncTask is designed to be a helper class around Thread and Handler and does not use a generic              threading framework.

     4.  AsyncTasks should ideally be used for short operations (a few seconds at the most.)

     5.  The AsyncTask class must be loaded on the UI thread.

     6. The task instance must be created on the UI thread.

     7.   execute(Params...)  must be invoked on the UI thread.


 Usage:

                         Taking same example as we have done in previous example Thread With Handlers - Android Example  In this example  we are creating a thread and call http GET method to get server response and after got the response,then do other functionality ( Save Data in database or show alert ,Redirect to another activity).


Program Code  :

  Asyncronoustask.class

public class Asyncronoustask extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.example);
        
         
        final Button GetServerData = (Button) findViewById(R.id.btuserver);
        
        GetServerData.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String serverURL = "http://www.mobile-tech.in/"; 
new LongOperation().execute(serverURL);
}
        });
        
    }
    
    private class LongOperation  extends AsyncTask<String, Void, Void> {
   
        private final HttpClient Client = new DefaultHttpClient();
        private String Content;
        private String Error = null;
        private ProgressDialog Dialog = new ProgressDialog(Asyncronoustask.this);
        TextView uiUpdate = (TextView) findViewById(R.id.output);
        protected void onPreExecute() {
       
        uiUpdate.setText("Output : ");
            Dialog.setMessage("Downloading source..");
            Dialog.show();
        }

        protected Void doInBackground(String... urls) {
            try {
           
           
      HttpGet httpget = new HttpGet(urls[0]);
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                Content = Client.execute(httpget, responseHandler);
                
            } catch (ClientProtocolException e) {
                Error = e.getMessage();
                cancel(true);
            } catch (IOException e) {
                Error = e.getMessage();
                cancel(true);
            }
            
            return null;
        }
        
        protected void onPostExecute(Void unused) {
       
            Dialog.dismiss();
            
            if (Error != null) {
                
                uiUpdate.setText("Output : "+Error);
                
            } else {
           
            uiUpdate.setText("Output : "+Content);
           
             }
        }
        
    }
}


Main.xml  :

 <Button 
        android:paddingTop="10px"
        android:id="@+id/btuserver" 
    android:text="Get Data Server " 
    android:cursorVisible="true"
    android:clickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"  
android:layout_gravity="center_horizontal"
    /> 
    
    <TextView
        android:paddingTop="20px"
        android:id="@+id/output"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Data Will Display here" />



Out Put :

1.       


2 .    


3 .      


Sunday 6 October 2013


Using Intent Flags


When starting an activity, you can modify the default association of an activity to its task by including flags in the intent that you deliver to startActivity(). The flags you can use to modify the default behavior are:





FLAG_ACTIVITY_NEW_TASK

                     Start the activity in a new task. If a task is already running for the activity you are now starting, that task is brought to the foreground with its last state restored and the activity receives the new intent in   onNewIntent().
This produces the same behavior as the "singleTask" launchMode value, discussed in the previous section.


FLAG_ACTIVITY_SINGLE_TOP

             If the activity being started is the current activity (at the top of the back stack), then the existing instance receives a call to onNewIntent(), instead of creating a new instance of the activity.
This produces the same behavior as the "singleTop" launchMode value, discussed in the previous section.


FLAG_ACTIVITY_CLEAR_TOP

            If the activity being started is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it are destroyed and this intent is delivered to the resumed instance of the activity (now on top), through onNewIntent()).
There is no value for the launchMode attribute that produces this behavior.

FLAG_ACTIVITY_CLEAR_TOP is most often used in conjunction with FLAG_ACTIVITY_NEW_TASK. When used together, these flags are a way of locating an existing activity in another task and putting it in a position where it can respond to the intent.


Friday 23 August 2013

READ THE FILE AND IMAGE FROM ASSERT FOLDER   :

In This code you read the file and Image from Assert folder 

Main.Class File:


public void onCreate(Bundle savedInstanceState) {

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


TextView readtext = (TextView) findViewById(R.id.readtext);
ImageView image = (ImageView) findViewById(R.id.image);

AssetManager assetManager = getAssets();
InputStream input;
        
     // To read the text file from assert
try {
input = assetManager.open("helloworld.txt");

        int size = input.available();
        byte[] buffer = new byte[size];
        input.read(buffer);
        input.close();

        String text = new String(buffer);

        readtext.setText(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// To get the image from assert
    try {
    InputStream ims = assetManager.open("android.jpg");
    Drawable d = Drawable.createFromStream(ims, null);
    image.setImageDrawable(d);
    }
    catch(IOException ex) {
    return;
    }
}

}


Main.xml:

   <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/image"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/readtext"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>


Screen Short :





Thursday 25 April 2013

Create Our Own App Lancher


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"
    android:background="@drawable/bg">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Purple App Lancher"
        android:layout_gravity="center"
        android:layout_marginTop="15dp"
        android:textStyle="bold"
        android:textSize="30sp"
        android:textColor="#2E0854" />
        <ListView 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@android:id/list"
            android:layout_marginLeft="200dp"
            android:layout_marginRight="200dp"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:background="@drawable/purple"/>
             
</LinearLayout>
   

row.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
       
        <ImageView
                android:id="@+id/app_icon"
                android:layout_width="48px"
                android:layout_height="48px"
                android:padding="3px"
                android:scaleType="fitXY"/>
       
        <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">
               
                <TextView
                        android:id="@+id/app_name"
                        android:layout_width="fill_parent"
                        android:layout_height="fill_parent"
                        android:gravity="center_vertical"
                        android:textColor="#fff"/>
       
        </LinearLayout>
</LinearLayout>


MainActivity:


package com.example.applauncher;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class AppLauncher extends ListActivity {
PackageManager packageManager = null;
List<ApplicationInfo> applist = null;
ApplicationAdaptor listadaptor = null;

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

packageManager = getPackageManager();

new LoadApplicationTask().execute();
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);

ApplicationInfo app = applist.get(position);


try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);

if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(AppLauncher.this, e.getMessage(), Toast.LENGTH_LONG)
.show();
} catch (Exception e) {
Toast.makeText(AppLauncher.this, e.getMessage(), Toast.LENGTH_LONG)
.show();
}

}

private List<ApplicationInfo> checkForLaunchIntent(
List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();

for (ApplicationInfo info : list) {
if (info.packageName.startsWith("com.test")) {

try {
if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
applist.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

return applist;
}

private class LoadApplicationTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;

@Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager
.getInstalledApplications(PackageManager.GET_META_DATA));

listadaptor = new ApplicationAdaptor(AppLauncher.this,
R.layout.row, applist);

return null;
}

@Override
protected void onCancelled() {
super.onCancelled();
}

@Override
protected void onPostExecute(Void result) {
setListAdapter(listadaptor);

progress.dismiss();

super.onPostExecute(result);
}

@Override
protected void onPreExecute() {
progress = ProgressDialog.show(AppLauncher.this, null,
"Loading application info...");

super.onPreExecute();
}

@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}

private class ApplicationAdaptor extends ArrayAdapter<ApplicationInfo> {
private List<ApplicationInfo> objects = null;

public ApplicationAdaptor(Context context, int textViewResourceId,
List<ApplicationInfo> objects) {
super(context, textViewResourceId, objects);

this.objects = objects;
}

@Override
public int getCount() {
return ((null != objects) ? objects.size() : 0);
}

@Override
public ApplicationInfo getItem(int position) {
return ((null != objects) ? objects.get(position) : null);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;

if (null == view) {
LayoutInflater vi = (LayoutInflater) AppLauncher.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.applauncherrow, null);
}

ApplicationInfo data = objects.get(position);

if (null != data) {
TextView textName = (TextView) view.findViewById(R.id.app_name);
ImageView iconview = (ImageView) view
.findViewById(R.id.app_icon);

textName.setText(data.loadLabel(packageManager) + " ("
+ data.packageName + ")");
iconview.setImageDrawable(data.loadIcon(packageManager));
}

return view;
}
};
}



in the above text color ,there you can give you own package name



Sunday 10 February 2013

  Android Blink Text :


Main Activity :

import android.app.Activity;

import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        blinkText();
     
    }
 
    private void blinkText(){
        final Handler handler = new Handler();
        new Thread(new Runnable() {
            public void run() {
            int timeToBlink = 1000;  
            try{
            Thread.sleep(timeToBlink);
        }catch (Exception e) {
       
        }
            handler.post(new Runnable() {
                public void run() {
                    TextView txt = (TextView) findViewById(R.id.tv);
                    if(txt.getVisibility() == View.VISIBLE){
                        txt.setVisibility(View.INVISIBLE);
                    }else{
                        txt.setVisibility(View.VISIBLE);
                    }
                    blinkText();
                }
                });
            }}).start();
   }
 
    public void blinkText2(){
    TextView myText = (TextView) findViewById(R.id.tv );

    Animation anim = new AlphaAnimation(0.0f, 1.0f);
    anim.setDuration(50);
    anim.setStartOffset(20);
    anim.setRepeatMode(Animation.REVERSE);
    anim.setRepeatCount(Animation.INFINITE);
    myText.startAnimation(anim);
    }
 

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

main.xlm :

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world"
        tools:context=".MainActivity"
        android:id="@+id/tv" />
    
</RelativeLayout>




Android Blink Animation as LED Bulb :


 Create  a new folder in res  as anim-->

 tween.xml

<set >
<alpha
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromAlpha="0.0"
    android:toAlpha="1.0"
    android:duration="100"
    android:repeatMode="reverse"
    android:repeatCount="infinite" />
</set>

main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="#ffffff" >

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="80dp" >

        <FrameLayout
            android:id="@+id/rightIcon"
            android:layout_width="30.0dip"
            android:layout_height="30.0dip" >

            <ImageView
                android:id="@+id/bsecond"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:scaleType="fitXY"
                android:src="@drawable/img_red"
                android:visibility="visible" />

            <ImageView
                android:id="@+id/afirst"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:scaleType="fitXY"
                android:src="@drawable/img_yellow"
                android:visibility="visible" />
        </FrameLayout>

        <FrameLayout
            android:id="@+id/rightIcon"
            android:layout_width="30.0dip"
            android:layout_height="30.0dip" >

            <ImageView
                android:id="@+id/bfourth"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:scaleType="fitXY"
                android:src="@drawable/img_green"
                android:visibility="visible" />

            <ImageView
                android:id="@+id/athird"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:scaleType="fitXY"
                android:src="@drawable/img_red"
                android:visibility="visible" />
        </FrameLayout>

        <FrameLayout
            android:id="@+id/rightIcon"
            android:layout_width="30.0dip"
            android:layout_height="30.0dip" >

            <ImageView
                android:id="@+id/bsix"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:scaleType="fitXY"
                android:src="@drawable/img_red"
                android:visibility="visible" />

            <ImageView
                android:id="@+id/afifth"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:scaleType="fitXY"
                android:src="@drawable/img_green"
                android:visibility="visible" />
        </FrameLayout>

        <FrameLayout
            android:id="@+id/rightIcon"
            android:layout_width="30.0dip"
            android:layout_height="30.0dip" >

            <ImageView
                android:id="@+id/bsecond"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:scaleType="fitXY"
                android:src="@drawable/img_red"
                android:visibility="visible" />

            <ImageView
                android:id="@+id/cfirst"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:scaleType="fitXY"
                android:src="@drawable/img_yellow"
                android:visibility="visible" />
        </FrameLayout>

        <FrameLayout
            android:id="@+id/rightIcon"
            android:layout_width="30.0dip"
            android:layout_height="30.0dip">

            <ImageView
                android:id="@+id/bsix"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:scaleType="fitXY"
                android:src="@drawable/img_red"
                android:visibility="visible" />

            <ImageView
                android:id="@+id/cfifth"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:scaleType="fitXY"
                android:src="@drawable/img_green"
                android:visibility="visible" />
        </FrameLayout>

  </TableRow>

</RelativeLayout>


MainActivity


import android.app.Activity;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

public class MainActivity extends Activity {

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

private void animate() {

ImageView myImageView4 = (ImageView) findViewById(R.id.afirst);
ImageView myImageView5 = (ImageView) findViewById(R.id.athird);
ImageView myImageView6 = (ImageView) findViewById(R.id.afifth);
ImageView myImageView7 = (ImageView) findViewById(R.id.cfirst);
ImageView myImageView9 = (ImageView) findViewById(R.id.cfifth);


Animation myFadeInAnimation = AnimationUtils.loadAnimation(
MainActivity.this, R.anim.tween);

myImageView4.startAnimation(myFadeInAnimation);
myImageView5.startAnimation(myFadeInAnimation);
myImageView6.startAnimation(myFadeInAnimation);
myImageView7.startAnimation(myFadeInAnimation);
myImageView9.startAnimation(myFadeInAnimation);

}

}

OutPut :


     





Monday 21 January 2013

Android Simple ToggleButton Saving the ON/OFF Example


I use two Activity ,in first used  button in second activity ToggleButton.

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

    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/textView1"
        android:layout_marginRight="75dp"
        android:layout_marginTop="120dp"
        android:text="Button" />

</RelativeLayout>

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

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ToggleButton" />

</LinearLayout>


..............................MainActivity.java.....................


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
Button button;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(getApplicationContext(), second.class));
}
});
}
}


.............................second.java........................................






import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.ToggleButton;

public class second extends Activity {

ToggleButton button;
SharedPreferences app_preferences;
SharedPreferences.Editor editor;
private static final String TOGGLE = "abc";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
button = (ToggleButton) findViewById(R.id.toggleButton1);
app_preferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
editor = app_preferences.edit();

if (app_preferences.getBoolean(TOGGLE, true)) {
button.setChecked(true);
} else {
button.setChecked(false);
}
// TODO Auto-generated method stub

button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (button.isChecked()) {
button.setChecked(true);
editor.putBoolean(TOGGLE, true);
} else {
button.setChecked(false);
editor.putBoolean(TOGGLE, false);
}
editor.commit();
}
});

}

}
Android Simple ToggleButton Example

SOURCE CODE [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" >

<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
    
<ToggleButton android:id="@+id/togglebutton"
android:layout_width="150px"
android:layout_height="50px"
android:textOn="ON"
android:textOff="OFF" />

</LinearLayout>

SOURCE CODE [ToggleButtonExample.java] is

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.ToggleButton;

public class ToggleButtonExample extends Activity
{

ToggleButton tb;

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
                                setContentView(R.layout.main);

                                tb = (ToggleButton) findViewById(R.id.togglebutton);
                                tb.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(getBaseContext(),
"Button is "+tb.getText().toString(),
Toast.LENGTH_LONG).show();
                                                }
                                });
                }
}




The OUTPUT