Did you heard aboout Android Alertbox or dialog box?But i am sure you have seen it several times on your android phone.A dialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed.See more about it here
In this post we are going to create an alertbox when user want to exit from your application.Its a very simple task to create an alertbox .Ok let us do it
STEP 1:
Create a new android studio project.Learn more about this step from this post
STEP 2:
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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next Activity"/>
</RelativeLayout>So this is our MainActivity.java
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}Add this to MainActivity.java
@Override
public void onBackPressed()
{
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit").setMessage("Sure you want to close this App").setPositiveButton("OK",new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog,int which)
{
Intent intent =new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
MainActivity.this.finish();
}
}).setNegativeButton("Cancel",null).show();
}
So our MainActivity.java will look like this
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onBackPressed()
{
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit").setMessage("Sure you want to close this App").setPositiveButton("OK",new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog,int which)
{
Intent intent =new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
MainActivity.this.finish();
}
}).setNegativeButton("Cancel",null).show();
}
}
No comments:
Post a Comment