How to not close AlertDialog android - java

Hi my problem is when I select an item my AlertDialog dismiss
alertDialog = new AlertDialog.Builder(getActivity());
alertDialog
.setSingleChoiceItems(ageArr, 1, btnSelectItem)
.setPositiveButton(R.string.dialog_ok, btnPositiveAgeDialog)
.setNegativeButton(R.string.dialog_cancel, null)
.show();
what my dialog click positive looks is.
private DialogInterface.OnClickListener btnSelectItem = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selectedIndexAge = which;
}
};
I tried setting the listener to null and it does not close but still
I needed it because I wanted to know which item is selected

Just put it
itemView.setOnClickListener(null);
or
You can use the implementation of hasOnClickListeners() for knowing the status of listener taken from android.view.View class for
public boolean hasOnClickListeners() {
ListenerInfo li = mListenerInfo;
return (li == null && li.mOnClickListener == null);
}
Use the following link for further modifications
Set listener instance in fragment on application restore

try this
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Boolean wantToCloseDialog = false;
//Do stuff, possibly set wantToCloseDialog to true then...
if(wantToCloseDialog)
dialog.dismiss();
//else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
}
});

Something else must be closing your AlertDialog. Below is a program that I believe duplicates the minimum requirements you have posted, and selecting one of the items does not close the dialog.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] values = new String[]{ "one", "two", "three", "four" };
DialogInterface.OnClickListener choiceListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "selected index: " + which, Toast.LENGTH_SHORT).show();
}
};
DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "positive button", Toast.LENGTH_SHORT).show();
}
};
new AlertDialog.Builder(this)
.setSingleChoiceItems(values, 1, choiceListener)
.setPositiveButton("ok", positiveListener)
.setNegativeButton("cancel", null)
.show();
}
}

Related

The button that I have created does not work. Is there something wrong with my code?

I am building an app in Android studio and basically I want a window to popup when a user clicks the add button. I used the setOnClickListener but when I run the app, nothing happens. Could there possibly something wrong with my code?
Here's my MainActivity code
public class MainActivity extends AppCompatActivity {
Button addBtn;
ListView itemListView;
DatePickerDialog.OnDateSetListener dateSetListener;
String dateString = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addBtn = (Button)findViewById(R.id.addBtn);
itemListView = (ListView)findViewById(R.id.itemListView);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
View view = getLayoutInflater().inflate(R.layout.activity_popup_window, null);
EditText itemName = (EditText)view.findViewById(R.id.itemName);
Button expirationDateBtn = (Button)view.findViewById(R.id.expirationDateBtn);
builder.setView(view)
.setTitle("Add Item")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (itemName.getText().toString().isEmpty() || dateString == null) {
Toast.makeText(MainActivity.this,
"Item name or expiration date is missing",
Toast.LENGTH_LONG).show();
}
else{
//do action
}
}
});
//when clicked on Expiration Date Btn
//display date on button
AlertDialogBuilder doesn't create and show a new AlertDialog implicitly. It only prepares the dialog before explicitly calling create() (or you can directly call show() if you need to display your dialog in the moment it gets built).
Your code misses the following lines at the end of onClick():
AlertDialog dialog = builder.create();
dialog.show();
or just:
builder.show();

Android: What is the best practice to organize methods to show alert dialog

I am beginner in Android development. Suppose I have some methods to show AlertDialog within an Activity. But each AlertDialog behavior is slightly different. What is the best practice to organize the methods to show AlertDiaolog?
code is like this.
private void showNumberPickerDialog() {
LayoutInflater inflater = this.getLayoutInflater();
View numberPickerDialogView = inflater.inflate(R.layout.number_picker, null);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Title for number picker here");
alertDialog.setCancelable(false);
alertDialog.setView(numberPickerDialogView);
final NumberPicker numberPicker = roomSizeNumberDialogView.findViewById(R.id.number_picker);
numberPicker.setMaxValue(10);
numberPicker.setMinValue(0);
numberPicker.setWrapSelectorWheel(false);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Something here
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
private void showMessageDialog(final boolean isA) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Title here");
alertDialog.setCancelable(false);
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (isA) {
doA();
} else {
doB();
}
}
});
alertDialog.show();
}
private void showAlertDialogC() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
final EditText inputEditText = new EditText(this);
inputEditText.setInputType(InputType.TYPE_CLASS_TEXT);
innputEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
alertDialog.setTitle("Title here");
alertDialog.setCancelable(false);
alertDialog.setView(nameEditText);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do something here
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
Is there a good way to organize the parts like this?
You can also use a customizable dialog if that's what you are looking for.
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_options);
dialog.show();
TextView tvDelete = dialog.findViewById(R.id.tvDelete);
tvDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
Dialog deleteDialog = new Dialog(context);
deleteDialog.setContentView(R.layout.dialog_delete);
deleteDialog.show();
}
});
Treat it just like you would treat an activity. Set onClickListeners on the views for which you want some particular actions. I believe this custom dialog is much more flexible than the AlertDialog
I like to handle my dialog in a separate class, that way you have more control over everything - clickListners, layout design, etc... and you don't have tons of code lines in your activity.
For example, create dialogClass:
public class ProgressDialog extends Dialog {
public ProgressDialog(#NonNull Context context) {
super(context);
setContentView(R.layout.progress_dialog); //this is your layout for the dialog
}
}
And all you need to do is to create dialog instant and call it like this:
ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.show(); // this line shows your dialog

close Alert Dialog without using negative Buttons

I created an AlertDialog, which will either refresh the activity (when btnConfirm1 is pressed), or does nothing and simply closes down (when btnDisconfirm1 is pressed). Everything is working apart from btnDisconfirm1. How can I close the dialog?
So apparently AlertDialog does not have a dismiss or cancel method, but is there another way without using negative buttons? The thing is, I created a layout file for this dialog and I don't know how to put a negative button in my xlm-file.
Or should I use a completely different approach apart from AlertDialog? Thanks!
btnClear = (Button) findViewById(R.id.btnClear);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder mBuilder2 = new AlertDialog.Builder(ScoreScreen.this);
View mView2 = getLayoutInflater().inflate(R.layout.dialog_confirm_delete, null);
Button btnConfirm1=(Button) mView2.findViewById(R.id.btnConfirm1);
Button btnDisconfirm1=(Button) mView2.findViewById(R.id.btnDisconfirm1);
btnConfirm1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
player1.setPlayerScore(0);
player2.setPlayerScore(0);
player3.setPlayerScore(0);
player4.setPlayerScore(0);
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
btnDisconfirm1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//WHAT DO I PUT HERE???
}
});
mBuilder2.setView(mView2);
AlertDialog dialog = mBuilder2.create();
dialog.show();
}
});
First you should create the AlertDialog with
AlertDialog mDialog = mBuilder2.create();
And secondly you can dismiss the dialog inside the OnClickListener with
mDialog.dismiss();
You can put this method in your Util class. and use callbacks
public interface OnDialogDismiss {
void onPositiveClick();
void onNegativeClick();
}
Modify it as your requirement.
public void showDialogForMultipleCallback(Context context, String title, String message, boolean cancellable, String neutralBbtn, String negativeBtn, String positiveBtn, final OnDialogDismiss onDialogDismiss) {
final AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setTitle(title);
builder1.setMessage(message);
builder1.setCancelable(cancellable);
if (neutralBbtn != null) {
builder1.setNeutralButton(neutralBbtn, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (alert11 != null)
alert11.dismiss();
}
});
}
if (negativeBtn != null) {
builder1.setNegativeButton(negativeBtn,
new OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (alert11 != null)
alert11.dismiss();
}
});
}
if (positiveBtn != null) {
builder1.setPositiveButton(positiveBtn, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
onDialogDismiss.onPositiveClick();
}
});
}
alert11 = builder1.create();
alert11.show();
}

Returning checked items from multi-choice dialog

By reading the documentation, I have managed to create a multiple choice dialog box. However, there's one bit that still has me completely stumped. When the user clicks "Okay", how do I return them to the parent Activity?
I"m referring to this particular comment:
// Set the action buttons
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
...
}
How exactly would I 'return them to the component that opened the dialog'?
My dialog call in my activity:
public void chooseTeam(View v) {;
DialogFragment newDialog = MultiChoiceDialog.newInstance(teamNamesArray);
newDialog.show(getFragmentManager(), "Choose_team");
}
and my dialog code:
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String[] team = getArguments().getStringArray("team");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.choose_team).setMultiChoiceItems(team, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
list.add(team[which]);
} else if (list.contains(team[which])) {
list.remove(team[which]);
}
}
}).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String selections = "";
for (String ms : list) {
selections = selections + "\n" + ms;
}
Toast.makeText(getActivity(), "Team Selected: " + selections,
Toast.LENGTH_LONG).show();
AddTaskActivity.chosenTeam = list;
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Toast.makeText(getActivity(), "Cancelled.", Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
You can make the ArrayList a class member variable like private ArrayList mSelectedItems;
See example code below
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ArrayList mSelectedItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSelectedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
// Set the dialog title
builder.setTitle(R.string.pick_toppings)
// Specify the list array, the items to be selected by default (null for none),
// and the listener through which to receive callbacks when items are selected
.setMultiChoiceItems(R.array.toppings, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
mSelectedItems.remove(Integer.valueOf(which));
}
}
})
// Set the action buttons
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
// in this case the OK button has more or less no function but if want save the check options in database or shared preference, you can put your code here. So it depends on your use case.
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
}
}

Java code optimalization - Two functions into one

Hello I have this code:
this.firstBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final CharSequence[] items = {"1", "2", "3"};
AlertDialog.Builder builder = new AlertDialog.Builder(SlovnikoidActivity.this);
builder.setTitle("test");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
langFrom.setText(items[item]);
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
this.secondBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final CharSequence[] items = {"1", "2", "3"};
AlertDialog.Builder builder = new AlertDialog.Builder(SlovnikoidActivity.this);
builder.setTitle("test");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
langFrom.setText(items[item]);
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
There are just two different parts: this.firstBtn and this.secondBtn
Is there a way how to merge it? For example when I click on firstBtn it calls a function foo(firstBtn) and secondBtn calls foo(secondBtn) and the rest would work the same?
I'm not sure about syntax etc. because I'm new to Java and Android development today.
Thanks
What you want can be done relatively easily. You can define a new class that implements OnClickListener, and use a new instance of this class in both locations.
class MyOnClickListener implements OnClickListener {
public void onClick(View v) {
final CharSequence[] items = {"1", "2", "3"};
AlertDialog.Builder builder = new AlertDialog.Builder(SlovnikoidActivity.this);
builder.setTitle("test");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
langFrom.setText(items[item]);
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
Your code can then look like this:
this.firstBtn.setOnClickListener(new MyOnClickListener());
this.secondBtn.setOnClickListener(new MyOnClickListener());
Obviously this solution can be taken further, if your two MyOnClickListener's need to be just slightly different. This can be done by creating a constructor that takes in the parameters that you want to change and store them as member variables, which are then used on the call to onClick(...):
class MyOnClickListener implements OnClickListener {
private CharSequence[] items;
public MyOnClickListener(CharSequence[] _items) {
items = _items;
}
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(SlovnikoidActivity.this);
builder.setTitle("test");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
langFrom.setText(items[item]);
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
And this can then be used like so:
final CharSequence[] items1 = {"1", "2", "3"};
final CharSequence[] items2 = {"2", "3", "4"};
this.firstBtn.setOnClickListener(new MyOnClickListener(items1));
this.secondBtn.setOnClickListener(new MyOnClickListener(items2));
UPDATE
public class SlovnikoidActivity extends Activity {
//slovnikoidActivity definition
//inner class definition for MyOnClickListener
class MyOnClickListener implements OnClickListener {
private CharSequence[] items;
public MyOnClickListener(CharSequence[] _items) {
items = _items;
}
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(SlovnikoidActivity.this);
builder.setTitle("test");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
langFrom.setText(items[item]);
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
As an alternative to nicholas.hauschild's answer, if you don't want to make a separate class, just make your activity implement View.OnClickListener.
Then, move your onClick(View v) method to the same class your button code is already in. If you need to distinguish between different buttons ever, then just do switch (v.getId()).

Categories