Run a function after dialog box is closed - android

I have a custom dialog box that I am displaying in the following way:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dict_add_word_dialog_box);
ok = findViewById(R.id.dictDialog_confirmButton);
cancel = (Button) findViewById(R.id.dictDialog_cancelButton);
ok.setOnClickListener(this);
cancel.setOnClickListener(this);
}
This displays when tapping the Floating Action Button, via:
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DictCustomDialogBoxClass customDialog = new DictCustomDialogBoxClass(DictionaryActivity.this);
customDialog.show();
refreshRecyclerView();
}
});
I'd like the refreshRecyclerView(); to run only once the user has pressed the OK button on the dialog box. How would I go about doing this?
In addition, how would I go about running it only if the user has pressed OK, and not Cancel?

Create a runnable with your refreshRecyclerView method in it:
Runnable r = new Runnable() {
#Override
public void run() {
refreshRecyclerView();
}
}
then create a handler for that runnable:
Handler handler = new Handler();
inside your onClickListener for the ok button trigger the runnable by calling the following:
handler.post(r);

Why not add a listener to your custom dialog?
var listener: Listener
public interface Listener {
void onPositiveActionPressed();
}
Then in your custom dialog's ok.onClickListener you'd have the below;
if(listener != null) {
listener.onPositiveActionPressed();
}
Finally;
DictCustomDialogBoxClass customDialog = new DictCustomDialogBoxClass(DictionaryActivity.this)
customDialog.listener = self
Of course having implemented DictCustomDialogBoxClass.Listener

Related

How to flipper a card (then back) in android

I have an ImageButton in my application.
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="80dp"
android:layout_height="80dp"
android:clickable="true"
android:src="#drawable/button" />
I bind it to an onClickListener:
View.OnClickListener imgButtonHandler = new View.OnClickListener() {
public void onClick(View v) {
// Here I update the image source to a different image.
}
};
Now what happens is: when I click the imagebutton, the imagebutton changes to a
different image. But I want it to change back automatically after 0.5 sec (during the
same time the user should not be able to click anything). How do I
implement that? I tried to sleep in the onClick function in the listener, but it's
not working...
New edit:
The proposed answer will solve my problem if I only have one imagebutton. I tried it out
and both work like charm!
Actually it is not working as expected. During that 500ms, the user still could click!
It is not solving the problem...
Posting a delayed runnable might do the job.
public void onClick(View v) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// change the background of the image button
(ImageButton)v.setBackgroundResource(R.drawable.someimage);
}
}, 500);
}
EDIT:
In fact, I've ran the following code on an actual device with two ImageButton and it works fine.
BTW, if you want the buttons to be un-clickable during the 500ms, just set it as imgBtn1.setClickable(false); and set it back to be clickable in the runnable as imgBtn1.setClickable(true);
public class TestFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.test_layout, container, false);
final ImageButton imgBtn1 = (ImageButton) view.findViewById(R.id.test_img_btn1);
final ImageButton imgBtn2 = (ImageButton) view.findViewById(R.id.test_img_btn2);
imgBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imgBtn1.setBackgroundResource(R.drawable.device_type_apple);
imgBtn1.setClickable(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// change the background of the image button
imgBtn1.setBackgroundResource(R.drawable.device_type_windows);
imgBtn1.setClickable(true);
}
}, 500);
}
});
imgBtn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imgBtn2.setBackgroundResource(R.drawable.device_type_apple);
imgBtn2.setClickable(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// change the background of the image button
imgBtn2.setBackgroundResource(R.drawable.device_type_android);
imgBtn2.setClickable(true);
}
}, 500);
}
});
return view;
}
}
You can use handle with runnable to auto update image
Handler mHandler = new Handler();
Runnable mUpdateTimer = new Runnable() {
#Override
public void run() {
// code update image here
// auto update after 0.5s
mHandler.postDelayed(mUpdateTimer, 500);
}
};
And when image button clicked:
View.OnClickListener imgButtonHandler = new View.OnClickListener() {
public void onClick(View v) {
mHandler.postDelayed(mUpdateTimer, 500);
}
};
Handler.postDelayed
this method is not good way ,see http://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable,long)
it say
Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the Runnable will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped.
so this methed may never invoke,it may be make you image button status never come back ,so you must be care the return value or use other widget ViewFliper,it can set animation when image switch and you can set delpoy .

Progress Dialog launches another AlertDialog

I want to show another alert message(alert box/alert dialog) after the progress bar reaches 100%. How do I do that?
And Also is there any way to style that box (or both of them)?
Below is my code for an ProgressBar:
public class MainActivity extends Activity {
Button progress_button;
ProgressDialog pro_dialog;
Handler pro_handler;
int progress;
private static final int MAX_PROGRESS = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// intiliazing the buttons
progress_button = (Button) findViewById(R.id.button1);
progress_button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Creating progress dialog interface setting
// title,progressstyle,max_progress
pro_dialog = new ProgressDialog(MainActivity.this);
pro_dialog.setTitle("Making everything OK is in progress! Please be patient.");
pro_dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pro_dialog.setMax(MAX_PROGRESS);
progress = 0;
pro_dialog.show();
pro_dialog.setProgress(0);
pro_handler.sendEmptyMessage(0);
}
});
// set onclick listener for buttons
pro_handler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (progress >= MAX_PROGRESS) {
pro_dialog.dismiss();
} else {
progress++;
pro_dialog.incrementProgressBy(2);
pro_handler.sendEmptyMessageDelayed(0, 100);
}
}
};
}
First of all, it would make more sense if you could replace:
pro_dialog.incrementProgressBy(2);
with this:
pro_dialog.setProgress(progress);
Current code dismisses dialog after progress variable reaches MAX_PROGRESS, but current value of this variable isn't presented by the progress dialog.
If you would like to show AlertDialog, you can do it for example after "pro_dialog.dismiss()".
Case of Progress Dialog styling has been discused here.

Return a value from Popup Window

I have popup window class like the following.
public class Popup extends PopupWindow {
Context context;
EditText et_bankname, et_banknumber;
String bank_name, account_number;
public Popup(Context ctx) {
super(ctx);
context = ctx;
setContentView(LayoutInflater.from(context).inflate(R.layout.bank_details, null));
setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
View popupView = getContentView();
setFocusable(true);
Button btn_close = (Button) popupView.findViewById(R.id.popupClose);
Button btn_submit = (Button) popupView.findViewById(R.id.popupSave);
et_bankname = (EditText) popupView.findViewById(R.id.bank_name);
et_banknumber = (EditText) popupView.findViewById(R.id.bankacc_no);
btn_submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
bank_name = et_bankname.getText().toString();
account_number = et_banknumber.getText().toString();
if (!bank_name.equals("") && !account_number.equals("")) {
Toast t1 = Toast.makeText(context,bank_name + " "+account_number , Toast.LENGTH_SHORT);
t1.setGravity(Gravity.TOP, 0, 100);
t1.show();
dismiss();
} else {
Toast t1 = Toast.makeText(context,
"Please provide valid details", Toast.LENGTH_SHORT);
t1.setGravity(Gravity.TOP, 0, 100);
t1.show();
}
}
});
}
public void show(View v) {
showAtLocation(v, Gravity.CENTER, 0, 0);
}
}
I will access this popup in my activity by
Popup popup = new Popup(getBaseContext());
popup.show(arg1);
This works perfectly. But I want to know when this popup window gets dismissed. for this purpose now I am using Thread concept like following.
if (isPopupShowing) {
Thread thread = new Thread() {
#Override
public void run() {
while (isPopupShowing) {
if (!popup.isShowing()) {
isPopupShowing = false;
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
loadDSP(type);
}
});
}
}
}
};
thread.start();
}
But this thread will run continuesly until the popup window gets dismissed. So I feel it is better to replace this solution by any other way.
What I want?
Just intimate to my activity like "popup is closed" when popup is dismissed.
Why I am use this way?
I will use this popup window in three activty. That is why I am create a separate class for popup window.
Any help will be highly appriciated.
Thank you.
PopupWindow already has its own dismiss listener, just use it as follows
Popup popup = new Popup(getBaseContext());
popup.show(arg1);
Change that to
Popup popup = new Popup(getBaseContext());
popup.setOnDismissListener(new PopupWindow.OnDismissListener() {
#Override
public void onDismiss() {
// Do your action
}
});
popup.show(arg1);
EDIT
I hadn't noticed you were extending a PopupWindow, which already has this implemented as shown in #Jayabal's answer. Anyway this is how you would do it if the PopupWindow didn't already have it's own onDismissListener.
Simply create your own OnDismissListener Interface.
public interface onDismissListener{
public void onDismiss();
}
Add a reference to a Listener in the PopUp class and a setter.
OnDismissListener listener;
public void setOnDismissListener(OnDismissListener listener){
this.listener = listener;
}
Then in your Activity
Popup popup = new Popup(getBaseContext());
popup.setOnDismissListener(new OnDismissListener(){
public void onDismiss(){
//do what you need to here
}
});
popup.show(arg1);
This pattern should be familiar to you, its used everywhere in Android.

Android Dialog dismisses instead of cancel

I'm having the following issue developing in android 2.2 (API 8):
I have a customized Dialog class like this:
public AuthDialog(final Context context, OnDismissListener dismissListener, OnCancelListener cancelListener) {
super(context);
setOnDismissListener(dismissListener);
setOnCancelListener(cancelListener);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.userpassdialog);
setTitle("Enter email and password");
setCancelable(true);
setCanceledOnTouchOutside(true);
authEmail = (EditText) findViewById(R.id.authEmail);
authPass = (EditText) findViewById(R.id.authPass);
alertMessage = (TextView) findViewById(R.id.auth_alert);
Button authButton = (Button) findViewById(R.id.authButton);
View.OnClickListener onClickListener = new View.OnClickListener() {
public void onClick(View v) {
if (checkCredentials())
dismiss();
else
showAlert();
}
};
authButton.setOnClickListener(onClickListener);
}
private void showAlert() {
alertMessage.setText("Wrong user/pass");
authEmail.setText(null);
authPass.setText(null);
}
private boolean checkCredentials() {
// Empty user/pass for now
boolean checkEmail = authEmail.getText().toString().equals("");
boolean checkPassword = authPass.getText().toString().equals("");
return checkEmail && checkPassword;
}
#Override
public void onBackPressed() {
cancel();
}
And I create a new AuthDialog like this:
private void authenticateThenAccept() {
OnDismissListener dismissListener = new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
accept();
}
};
OnCancelListener cancelListener = new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
cancel();
}
};
AuthDialog dialog = new AuthDialog(context, dismissListener, cancelListener);
dialog.show();
}
I'm using the debugger, and I see that when I cancel (using the back button or pressing outside the dialog) the app dismisses the dialog instead of cancelling.
Anybody has had this kind of issue with Dialogs?
Thanks in advanced.
onDismiss() is always fired when dialog closes. The documentation for setOnCancelListener() states: "This will only be invoked when the dialog is canceled, if the creator needs to know when it is dismissed in general, use setOnDismissListener", i.e. it's not either onCancel or onDismiss but both when a dialog is canceled. I agree though that it would have made more sense had that not been the case.
Assuming this dialog should be modal, make your dialog a new activity.
setCancelable(false) will prevent the back button from doing anything. Many developers just turn off the ability of the back button to close the dialog since it's unclear whether that is a cancel or ok action to the user.

Button on Custom Dialog Not Responding to Click Events

I created a custom dialog that extends Dialog. One button on that the dialog is an “OK” button which the user is expected to press when finished entering information in other fields. I cannot get any listeners set to that button to fire.
public class HeightDialog extends Dialog {
private Button okButton;
…
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.heightdialog);
this.okButton = (Button)this.findViewById(R.id.userOkWithHeight);
this.okButton.setOnClickListener(new android.view.View.OnClickListener() {
public void onClick(View v) {
// Does not fire
HeightDialog.this.dismiss();
return;
}
});
this.okButton.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
// Does not fire
HeightDialog.this.dismiss();
return true;
}
});
this.okButton.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// Does not fire
HeightDialog.this.dismiss();
return true;
}
});
…
}
I also attempted an implementation where the Dialog class implemented the listeners(http://www.androidcompetencycenter.com/2009/01/android-basics-dialogs-and-floating-activities/) instead of using inner classes(http://about-android.blogspot.com/2010/02/create-custom-dialog.html):
Still no luck.
public class HeightDialog extends Dialog implements View.OnClickListener {
private Button okButton;
…
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.heightdialog);
this.okButton = (Button)this.findViewById(R.id.userOkWithHeight);
this.okButton.setOnClickListener(this);
public void onClick(View view){
HeightDialog.this.dismiss();
return;
}
…
}
I have set breakpoints inside each of the listeners in both versions of the implementation, and the debugger never stops execution. I have attempted to use inner classes for the listeners which did not solve the problem.
Any clues?
Thanks
I found a solution here:
Handling buttons in custom dialogs
It works in my case.
dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Dialog");
Button dialog_btn = (Button) dialog.findViewById(R.id.dialog_button);
dialog_btn.setOnClickListener(new View.OnClickListener()
{
// Perform button logic
}
Why I am not sure why following the two examples mentioned in my post did not work, I figured out how to get it to work. I had to move the attachment of my listener to the button in the dialog's onStart() method from the dialog's onCreate() method.
It appear this is related to me also overriding the onStart() method in my custom dialog:
public void onStart() {
super.onStart();
setContentView(R.layout.heightdialog);
...
}
That code must have "zeroed" out my listeners which were in the onCreate() method.
In order to intercept button clicks HeightDialog must implement View.OnClickListener
public class HeightDialog extends Dialog implements View.OnClickListener
{
}

Categories

Resources