Follow Below Steps.
1. Create New Android Project. Name It Exit as i did.
2. Now Open Your activity_main.xml. Follow Path .res --> Layout --> activity_main.xml.
I Have Added Analog Clock To Graphical Layout Because I don't Wanted To left screen as blank so..
You May Left Your Screen Blank For Now.
3. Type Below Code To Your activity_main.xml
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_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="64dp"
android:layout_marginTop="37dp" />
</RelativeLayout>
4. Open Your MainActivity.java File And Type Below code.
MainActivity.java
package arshad.exit;
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);
}
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Do you want
to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new
DialogInterface.OnClickListener() {
public void
onClick(DialogInterface dialog, int id) {
MainActivity.this.finish();
}
})
.setNegativeButton("No", null)
.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;
}
}
5. Now Compile And Run Your Project As Android Application.
6. When Your Application Executes Press Back Button. The Alert Box Will Ask To Exit.
My Output Screen's Are As Below.
No comments:
Post a Comment