Wednesday, 28 December 2011

How To Create An Alert Box in Android.


Create a "main.xml" data in your layout folder.


<LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:weightSum="1"><Button android:id="@+id/button1" android:text="Button" android:layout_height="wrap_content" android:layout_width="wrap_content"/></LinearLayout>

................................................................................................................................




Use the following code in your .java page (class file)


Here (AlertActivity.java)




public class AlertActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(AlertActivity.this);
builder.setMessage("are you sure want to exit");
builder.setCancelable(false);
builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
 
@Override
public void onClick(DialogInterface dialog, int which) {

AlertActivity.this .finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();

}

});
        
        
    }
}
..........................................................................................................................................................

AndroidManifest.xml


<manifest package="com.alert" android:versionCode="1" android:versionName="1.0"><uses-sdk android:minSdkVersion="10"/><application android:icon="@drawable/bea" android:label="@string/app_name"><activity android:name=".AlertActivity" android:label="@string/app_name"><intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter></activity></application></manifest>


...............................................................................................................................................................


No comments:

Post a Comment