How to customize pop up notifications? - android

When you click on the image button, pop up notification pops up. How do I customize the "ok" and "cancel" button to instead of using the default look of the buttons, I want to use my own custom ImageButtons as "ok" and "cancel".
Here's my code for pop up notification.
public class Notifications extends AppCompatActivity {
ImageButton Notifications;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notifications);
Notifications = (ImageButton) findViewById(R.id.AllowNotifications);
Notifications.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(Notifications.this);
builder.setCancelable(false); //False= ONLY way to exist notification is by clicking NO
//True= Exit notification by clicking anywhere on screen outside of notification box.
builder.setTitle("Here is the alert dialog");
builder.setMessage("Here is my message thing");
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int WhichButton) {
dialog.cancel();
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
});
}
}
Here's the default pop up notification with the above code:
So instead of there being an "ok" and "cancel" in red color, I want to put the "ok" and "cancel" as my own custom image buttons and I'd want to change the color from red to something else. How do I go about doing this inside the Pop Up notification?

As the documentation says, in the Creating a Custom Layout session, you can create a custom layout and inflate it at your Dialog.
To use another button than the one create by the AlertDialog.Builder you will need to handle the click listener of them.
This is the layout I created to test the solution:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#android:color/white"
android:orientation="vertical"
android:padding="20dp">
<TextView
android:id="#+id/dialogTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Here is the alert dialog"
android:textColor="#android:color/black"
android:textSize="16sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/dialogSubtitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Here is my message thing"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp">
<Button
android:id="#+id/positiveButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:background="#android:color/transparent"
android:text="OK"
android:textColor="#android:color/holo_red_light"/>
<Button
android:id="#+id/negativeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="40dp"
android:layout_toStartOf="#id/positiveButton"
android:background="#android:color/transparent"
android:text="Cancel"
android:textColor="#android:color/holo_red_light"/>
</RelativeLayout>
</LinearLayout>
And the code to make it run:
LayoutInflater layoutInflater = LayoutInflater.from(this);
View promptView = layoutInflater.inflate(R.layout.test, null);
final AlertDialog alertD = new AlertDialog.Builder(this).create();
TextView title = (TextView) promptView.findViewById(R.id.dialogTitle);
TextView subtitle = (TextView) promptView.findViewById(R.id.dialogSubtitle);
title.setText("My new Custom Dialog");
subtitle.setText("With everything that I want");
Button positive = (Button) promptView.findViewById(R.id.positiveButton);
Button negativeButton = (Button) promptView.findViewById(R.id.negativeButton);
positive.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// btnAdd1 has been clicked
}
});
negativeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// btnAdd2 has been clicked
}
});
alertD.setView(promptView);
alertD.show();
This is an screenshot of how it looks like in my phone. Feel free to change the layout in the way it better fits your needs.
Thanks to Vikram that explains it very well in this answers for other question, but I thought that a specific code for your question would be better.

If you want to customize everything, the look of the dialog, add your own buttons, TextViews etc. - you need to make a class that extends DialogFragment and implements View.OnClickListener and you need to create your own layout with two custom made buttons for that. Give them ids and set OnClickListeners
As typed in: https://developer.android.com/reference/android/app/DialogFragment.html
public static class MyDialogFragment extends DialogFragment implements View.OnClickListener {
static MyDialogFragment newInstance() {
return new MyDialogFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dialog_fragment, container, false);
v.findViewById(R.id.btn_ok).setOnClickListener(this);
return v;
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_ok:
// do something
break;
default:
break;
}
}
}
And from your Activity you do:
void showDialog() {
// Create the fragment and show it as a dialog.
DialogFragment newFragment = MyDialogFragment.newInstance();
newFragment.show(getFragmentManager(), "dialog");
}

Related

How to customize the Title Section of a Dialog

I have created a customized dialog and applied the layout xml to it. But the layout is always applied to the body of the dialog and never to the title section. All what I can do is to set the title of the dilaog programmatically using setTitle and add an icon using setFeatureDrawableResource. Please let me know how to customize the title section of a customized dialog?
Side Question: today when I accessed my stackoverflow account I found that, there are more than 200 points are deducted? any Idea why?
Java_Code:
reportDialog = new Dialog(MeetingPointFix.this);
reportDialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
reportDialog.setCancelable(false);
LayoutInflater reportAlertDialogLayoutInflater = LayoutInflater.from(getApplicationContext());
View reportAlertDialogInflatedView = reportAlertDialogLayoutInflater.inflate(R.layout.meetingpointfix_report_dialog, null);
reportDialog.setContentView(reportAlertDialogInflatedView);
int [] viewsRefsIds = {R.id.reportLocNameValue, R.id.reportLocLatValue, R.id.reportLocLngValue, R.id.reportTimeValue,
R.id.reportDateValue, R.id.reportImgTitleValue, R.id.reportImgPathValue
};
reportDialog.setTitle(REPORT_ALERT_DIALOG_TITLE);
reportDialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,R.drawable.reporticon01);
TextView reportDialogMSG = (TextView) reportDialog.findViewById(R.id.reportDialogMessageValue);
Button reportOkBtn = (Button) reportDialog.findViewById(R.id.reportOkBtnID);
Button reportNavigateBtn = (Button) reportDialog.findViewById(R.id.reportNavigateBtnID);
Yes , I agree that some times the default dialog title doesn'nt match the theme style of your app .
Luckily android provides you a way to update the title layout you just need to take care of these three lines of code while you are creating your dialog.
dialog.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
dialog.setContentView(R.layout.test);
dialog.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.dialog_title_test);
Make sure that the call to setContentView() occurs after requestWindowFeature() and before setFetureInt()
So , suppose for a dialog Fragment you can do that as
public class DialogTest extends DialogFragment{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
dialog.setContentView(R.layout.test);
dialog.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.dialog_title_test);
return dialog;
}
}
Happy Coding ! :)
add the following to your styles xml file:
<style name="FullHeightDialog" parent="android:style/Theme.Dialog">
<item name="android:windowNoTitle">true</item>
</style>
use this to create the dialog (modify as you wish and set your ids for buttons)
private void showDialog() {
final Dialog dialog = new Dialog(this, R.style.FullHeightDialog);
dialog.setContentView(R.layout.alert_dialog); //replace with your layout xml
dialog.setCancelable(false);
Button ignoreButton = (Button) dialog.findViewById(R.id.ignore_button);
ignoreButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
Button answerButton = (Button) dialog.findViewById(R.id.answer_button);
answerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
The easiest way would be to use this library. I read other answers in this post and wanted to add one like to the code similar to theirs. You can provide custom title bar in your layout file itself. See this code:
public void createDialogLanguage() {
ListView listViewLanguage;
final Dialog dialog = new Dialog(getActivity());
dialog.getWindow().addFlags(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawableResource(
android.R.color.transparent);
dialog.setContentView(R.layout.dialog_language);
dialog.show();
}
Please note this line:
dialog.getWindow().setBackgroundDrawableResource(
android.R.color.transparent);
This causes your dialog border and title bar to be transparent. It is useful if you are setting custom background with border(mycase: rounded corners) to display appropriately. No edges visible.
To customize completely your Dialog the best would be probably to extend it and create a custom Dialog.
This will give you all the freedom that you need, but of course you have to do more work.
public class MyDialog extends Dialog {
public MyDialog(Context context) {
super(context, android.R.style.Theme_Black_NoTitleBar);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setCanceledOnTouchOutside(false);
setContentView(R.layout.my_dialog_layout);
TextView title = (TextView) findViewById(R.id.my_dialog_title);
title.setText(context.getString(R.string.my_dialog_title_text));
findViewById(R.id.error_dialog_btn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something
MyDialog.this.dismiss();
}
});
findViewById(R.id.success_dialog_btn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something
MyDialog.this.dismiss();
}
});
}
}
You need to create a custom AlertDialog for this:
public class CustomAlertDialogBuilder extends AlertDialog.Builder {
private final Context mContext;
private TextView mTitle;
private ImageView mIcon;
private TextView mMessage;
public CustomAlertDialogBuilder(Context context) {
super(context);
mContext = context;
View customTitle = View.inflate(mContext, R.layout.dialog_title, null);
mTitle = (TextView) customTitle.findViewById(R.id.alertTitle);
mIcon = (ImageView) customTitle.findViewById(R.id.icon);
setCustomTitle(customTitle);
}
#Override
public CustomAlertDialogBuilder setTitle(int textResId) {
mTitle.setText(textResId);
return this;
}
#Override
public CustomAlertDialogBuilder setTitle(CharSequence text) {
mTitle.setText(text);
return this;
}
#Override
public CustomAlertDialogBuilder setIcon(int drawableResId) {
mIcon.setImageResource(drawableResId);
return this;
}
#Override
public CustomAlertDialogBuilder setIcon(Drawable icon) {
mIcon.setImageDrawable(icon);
return this;
}
}
You also need a custom layout:
res/layout/dialog_title.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"
android:orientation="vertical">
<LinearLayout
android:id="#+id/title_template"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:layout_marginTop="6dip"
android:layout_marginBottom="9dip"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip">
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingTop="6dip"
android:paddingRight="10dip"
android:src="#drawable/ic_dialog_alert" />
<TextView
android:id="#+id/alertTitle"
style="#style/?android:attr/textAppearanceLarge"
android:singleLine="true"
android:ellipsize="end"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<ImageView android:id="#+id/titleDivider"
android:layout_width="fill_parent"
android:layout_height="1dip"
android:scaleType="fitXY"
android:gravity="fill_horizontal"
android:src="#drawable/divider_horizontal_bright" />
</LinearLayout>
Hope this helps.
You can find more info here:
How to change theme for AlertDialog
FYI your StackOverflow account was created less than 24 hours ago, so it looks like you made a new account rather than accessing your original one.
Try this, This will definitly solve youre problem
AlertDialog.Builder builder = new AlertDialog.Builder(MeetingPointFix.this);
builder.setCancelable(false);
LayoutInflater reportAlertDialogLayoutInflater = LayoutInflater.from(getApplicationContext());
View reportAlertDialogInflatedView = reportAlertDialogLayoutInflater.inflate(R.layout.meetingpointfix_report_dialog, null);
builder.setView(reportAlertDialogInflatedView);
int [] viewsRefsIds = {R.id.reportLocNameValue, R.id.reportLocLatValue, R.id.reportLocLngValue, R.id.reportTimeValue,
R.id.reportDateValue, R.id.reportImgTitleValue, R.id.reportImgPathValue
};
builder.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,R.drawable.reporticon01);
TextView reportDialogMSG = (TextView) reportDialog.findViewById(R.id.reportDialogMessageValue);
Button reportOkBtn = (Button) reportDialog.findViewById(R.id.reportOkBtnID);
Button reportNavigateBtn = (Button) reportDialog.findViewById(R.id.reportNavigateBtnID);
reportDialog=builder.create();

Customizing android DialogFragment

iam a beginner level programmer in Android.Now iam after a small app development and i have a dialogFragment.Everything is perfectly working and its displaying Dialog box also.But i have some difficulties with color scheme. I have changed the background color of layout and but its title bar color remains same white and also title text color blue and a blue line under that(need to change it to green).How i can achieve this?
please help me
here is my fragment code
public class ClientInfofrag extends DialogFragment {
public ClientInfofrag()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.clientinfolayout, container);
getDialog().setTitle("Client Info");
return view;
}
}
Thank you
Since you are using the .setTitle() method it is only setting the title with the defualt settings, such as the white background. If you want to customize the title background color you will need to have an xml to do that. Also, for DialogFragments, from my knowledge and experience, you should use public Dialog onCreateDialog instead of public View onCreateView. That way you return a Dialog as opposed to just a View that you can then just call .show() on and it will display your dialog. Here is an example:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
Bundle args = getArguments();
currentName = args.getString(ARG_CURRENT_NAME);
builder.setView(inflater.inflate(R.layout.name_dialog, null));
builder.setTitle("Rename Rapper Program");
builder.setMessage("Enter a new name for " + currentName + ":");
builder.setPositiveButton("Rename", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
newName = (EditText) getDialog().findViewById(R.id.new_name);
newProgName = newName.getText().toString();
mRename.renameProgram(currentName, newProgName);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dismiss();
}
});
return builder.create();
}
Here is an example dialog xml, though it is not the xml that is being inflated in the above DialogFragment:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:drawableLeft="#drawable/login"
android:layout_width="match_parent"
android:layout_height="64dp"
android:background="#FCD116"
android:text="#string/login"
android:textSize="36sp"/>
<EditText android:id="#+id/username"
android:inputType="textEmailAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="#string/un"/>
<EditText android:id="#+id/password"
android:inputType="textPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="16dp"
android:fontFamily="sans-serif"
android:hint="#string/pw"/>
</LinearLayout>
The LinearLayout is setting up the rest of the child items to be placed accordingly. The first TextView acts as my "title" bar and then the EditTexts are the "body" of the dialog. I have no buttons in the xml because I set those programmatically within the onCreateDialog like in the other snippet of code above.
The example of the above (TronicZomB) could work if you disable the default windows title:
// Remove the title
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
Try it!

DialogFragment not floating, acts embeded or as another fragment

I have this app, that I created a custom dialog for. I must of goofed something up cause while the .show call on the dialog does indeed bring it up, it looks like a whole new fragment and it is not floating but instead replacing the ui with its contents. I did see in their help for DialogFragment:
http://hi-android.info/docs/reference/android/app/DialogFragment.html#Lifecycle
that one can embed a dialog as a regular fragment or not. Though I am not doing anything to do this so I cannot figure out why its acting like an embedded fragment and not floating. After thinking on it, is it the way I defined my XML definition? The dialogfragment example above didn't really give a definition for the xml layout, so maybe that is where my issue is? (Even added the gravity to the xml file, still no dice)
My xml definition for this Dialog is here:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textSize="20sp"
android:text = "Location:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"/>
<Spinner
android:id="#+id/location_spinner"
android:layout_width = "450sp"
android:layout_height="wrap_content"/>
<!-- fill out the data on the package total cost etc -->
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button android:id="#+id/location_dlg_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Okay"/>
<Button android:id="#+id/location_dlg_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"/>
<Button android:id="#+id/location_dlg_new"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create new..."/>
</LinearLayout>
</LinearLayout>
Like I said displays just fine, the code for the fragment:
package com.viciousbytes.studiotab.subactivities.dialogfragments;
import ... ...
public class LocationPicker extends DialogFragment {
ArrayList<Location> mLocations;
public static LocationPicker newInstance()
{
LocationPicker loc = new LocationPicker();
return loc;
}
private void setLocations(ArrayList<Location> loc)
{
mLocations=loc;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Pick a style based on the num.
int style = DialogFragment.STYLE_NORMAL, theme = android.R.style.Theme;
setStyle(style, theme);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.location_dialog, container, false);
Spinner spinner = (Spinner)v.findViewById(R.id.location_spinner);
ArrayAdapter<Location> adapter = new ArrayAdapter<Location>(v.getContext(), android.R.layout.simple_spinner_item, mLocations);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
if(mLocations==null)
spinner.setPrompt("No Locations");
else
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new LocationSelectedListener());
// Watch for button clicks.
Button newBtn = (Button)v.findViewById(R.id.location_dlg_new);
newBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// When button is clicked, call up to owning activity.
//create new start that activity...
}
});
// Cancel do nothing dismissthis
Button cancelBtn = (Button)v.findViewById(R.id.location_dlg_cancel);
cancelBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// When button is clicked, call up to owning activity.
//create new start that activity...
}
});
// okay button means set listener with the selected location.
Button okBtn = (Button)v.findViewById(R.id.location_dlg_ok);
okBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// When button is clicked, call up to owning activity.
//create new start that activity...
}
});
return v;
}
}
It is called from a fragment itself? though does that matter? because I am calling a TimePIckerDialog and a DatePickerDialog and those work fine, but my calling code from my other fragment is:
void showLocationDialog() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag("locpicker");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
DialogFragment newFragment = LocationPicker.newInstance();
newFragment.show(ft, "locpicker");
}
Your constructors are wrong. Try to have just one static method newInstance to instantiate the fragment for all cases and use a Bundle to store the arguments that you want to use in the fragment. Refer to Basic Dialog section here and extend it to your case.

How to configure custom button in dialog?

here I have a custom dialog with background 2 ImageButton inside it.
the problem is, when I try to set onclick listener to that buttons, the program will return NullPointerException. I don't know why is this happen. how to assign operation to button inside dialog anyway??
pause menu xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:id="#+id/linearLayout1" android:layout_width="wrap_content" android:background="#drawable/pause_menu_cropped" android:layout_gravity="center" android:gravity="center|center_horizontal">
<TableLayout android:layout_width="wrap_content" android:id="#+id/tableLayout1" android:layout_height="wrap_content">
<ImageButton android:src="#drawable/pause_button_option" android:layout_width="wrap_content" android:background="#drawable/pause_button_option" android:layout_height="wrap_content" android:id="#+id/btn_pause_option"></ImageButton>
<ImageButton android:src="#drawable/pause_button_quit" android:layout_width="wrap_content" android:background="#drawable/pause_button_quit" android:layout_height="wrap_content" android:id="#+id/btn_pause_quit"></ImageButton>
</TableLayout>
</LinearLayout>
dialog code
Dialog pauseMenu = new Dialog(this, R.style.NewDialog);
pauseMenu.setContentView(R.layout.pause_menu);
ImageButton quit = (ImageButton)findViewById(R.id.btn_pause_quit);
quit.setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
TestActivity.this.finish();
}
});
return pauseMenu;
the code is returning error in line
quit.setOnClickListener();
ImageButton quit =
(ImageButton)findViewById(R.id.btn_pause_quit);
should be
ImageButton quit = (ImageButton)pauseMenu.findViewById(R.id.btn_pause_quit);
This happens because findViewById is invoked for the activity, and it doesn't have btn_pause_quit button in it's layout. But your dialog has.
U can use this custom dialog and onclicklistener..
public class CustomizeDialog extends Dialog implements OnClickListener {
Button okButton;
public CustomizeDialog(Context context) {
super(context);
/** 'Window.FEATURE_NO_TITLE' - Used to hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
/** Design the dialog in main.xml file */
setContentView(R.layout.main);
okButton = (Button) findViewById(R.id.OkButton);
okButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
/** When OK Button is clicked, dismiss the dialog */
if (v == okButton)
dismiss();
}
}
I think your onClickListener should be DialogInterface.OnClickListener

How to keep an alertdialog open after button onclick is fired? [duplicate]

This question already has answers here:
How to prevent a dialog from closing when a button is clicked
(21 answers)
Closed 3 years ago.
The subject kinda says it all.. I'm requesting a PIN code from the user, if they enter it, click the OK Positive Button and the PIN is incorrect I want to display a Toast but keep the dialog open. At the moment it closes automatically.. Sure this is very trivial thing to correct but can't find the answer yet.
Thanks..
You do not need to create a custom class. You can register a View.OnClickListener for the AlertDialog. This listener will not dismiss the AlertDialog. The trick here is that you need to register the listener after the dialog has been shown, but it can neatly be done inside an OnShowListener. You can use an accessory boolean variable to check if this has already been done so that it will only be done once:
/*
* Prepare the alert with a Builder.
*/
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setNegativeButton("Button", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {}
});
this.alert = b.create();
/*
* Add an OnShowListener to change the OnClickListener on the
* first time the alert is shown. Calling getButton() before
* the alert is shown will return null. Then use a regular
* View.OnClickListener for the button, which will not
* dismiss the AlertDialog after it has been called.
*/
this.alertReady = false;
alert.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
if (alertReady == false) {
Button button = alert.getButton(DialogInterface.BUTTON_NEGATIVE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
alertReady = true;
}
}
});
Part of this solution was provided by http://groups.google.com/group/android-developers/browse_thread/thread/fb56c8721b850124#
Build a custom dialog with a EditText with the attribute android:password="true" a button, then manually set onClick listener the button, and explicitly choose what to do in it.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minWidth="180dip"
android:digits="1234567890"
android:maxLength="4"
android:password="true"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/Accept"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Accept"/>
</LinearLayout>
</LinearLayout>
Then when you want it to pop up:
final Dialog dialog = new Dialog(RealizarPago.this);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("PIN number:");
dialog.setCancelable(true);
Button button = (Button) dialog.findViewById(R.id.Accept);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(password_wrong){
// showToast
} else{
dialog.dismiss();
// other stuff to do
}
}
});
dialog.show();
You can set an OnClickListener as follows to keep the dialog open:
public class MyDialog extends AlertDialog {
public MyDialog(Context context) {
super(context);
setMessage("Hello");
setButton(AlertDialog.BUTTON_POSITIVE, "Ok", (new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// this will never be called
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ok) {
// do something
dismiss();
} else {
Toast.makeText(getContext(), "when you see this message, the dialog should stay open", Toast.LENGTH_SHORT).show();
}
}
});
}
}
You can just continue using the dialog you already have, just put an if clause in the onClick() saying
if(pin_check_method){ //pin_check_method should be a boolean returned method
//close the Dialog, then continue
}
else{
//dont put the dialog.dismiss() in here, put instead
Toast.makeText(getApplicationContext(),"Invalid pin, please try again",Toast.LENGTH_LONG).show();
}
Now, to use this code, simply invoke text.setText(""); and put in the text you want here
common error is that when you type in:
TextView text = (TextView) findViewById(R.id.dialog);
you miss that it needs to actually be
dialog.findViewById
and this is regardless of what the name of the dialog is, in my example it just happens to be the same name.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="#+id/text"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"/>
<Button android:text="Continue"
android:id="#+id/Button01"
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_below="#+id/text">
</Button>
</RelativeLayout>
Try this:
final AlertDialog alertDialog = new AlertDialog.Builder(context)
.setView(v)
.setTitle(R.string.my_title)
.setPositiveButton(android.R.string.ok, null) //Set to null. We override the onclick
.setNegativeButton(android.R.string.cancel, null)
.create();
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
Button b = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Do something
}
});
}
});
alertDialog.show();
Source: Prevent Alertdialog from closing after button click
Hope This Helps! Good Luck!
Same problem for me in a FragmentDialog. Here's my criminal/elegant solution:
Remove all buttons from the dialog (positive,negative,neutral). Add your buttons from the xml.eg.:
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="wrap_content">
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:id="#+id/button_cancel"
style="#style/Widget.AppCompat.Button.Borderless.Colored"
android:text="#android:string/cancel"
android:layout_gravity="left"
/>
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:id="#+id/button_ok"
style="#style/Widget.AppCompat.Button.Borderless.Colored"
android:text="#android:string/ok"
android:layout_gravity="right"
/>
</LinearLayout>
And then in your code handle it with:
view.findViewById(R.id.button_ok).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view2) {
if (wannaClose)
dismiss();
else
//do stuff without closing!
}
});
where view is the view assigned to the dialog!

Categories

Resources