Today I will introduce How to add a cancel button on Android AlertDialog for Android programmers, with simple steps that can help you create the most beautiful Alertdialog in android example.
Step 1. Create a file activity_main.xml
<RelativeLayoutStep 2. Create a class MainActivity.class
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".MainActivity"
android:background="#ecd235"
>
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a TextView."
android:textSize="35dp"
/>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Apply Red Color Text"
android:layout_below="@id/tv"
/>
</RelativeLayout>
public class MainActivity extends Activity {Result:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get reference of widgets from XML layout
final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
Button btn = (Button) findViewById(R.id.btn);
final TextView tv = (TextView) findViewById(R.id.tv);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Build an AlertDialog
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
// Set a title for alert dialog
builder.setTitle("Select your answer.");
// Ask the final question
builder.setMessage("Want to apply Red color on TextView?");
// Set click listener for alert dialog buttons
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch(which){
case DialogInterface.BUTTON_POSITIVE:
// User clicked the Yes button
tv.setTextColor(Color.RED);
break;
case DialogInterface.BUTTON_NEGATIVE:
// User clicked the No button
Toast.makeText(getApplicationContext(),
"Your answer is no.",Toast.LENGTH_SHORT).show();
break;
case DialogInterface.BUTTON_NEUTRAL:
// Neutral/Cancel button clicked
Toast.makeText(getApplicationContext(),
"You clicked Cancel button.",Toast.LENGTH_SHORT).show();
break;
}
}
};
// Set the alert dialog yes button click listener
builder.setPositiveButton("Yes", dialogClickListener);
// Set the alert dialog no button click listener
builder.setNegativeButton("No",dialogClickListener);
// Set the alert dialog cancel/neutral button click listener
builder.setNeutralButton("Cancel", dialogClickListener);
AlertDialog dialog = builder.create();
// Display the three buttons alert dialog on interface
dialog.show();
}
});
}
}
No comments:
Post a Comment