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();
}
});
}
}
Related
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();
}
}
Iam creating a dialog with following code, who creates multiple choice check box.. But I don't know how to create their id's to add click event , I m new to android please help me..:
private void showDailog() {
final String[] items = {" Blue", " Red", " Black", " White", " Pink"};
final ArrayList itemsSelected = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select any theme you want : ");
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int selectedItemId,
boolean isSelected) {
if (isSelected) {
itemsSelected.add(selectedItemId);
} else if (itemsSelected.contains(selectedItemId)) {
itemsSelected.remove(Integer.valueOf(selectedItemId));
}
}
})
.setPositiveButton("Done!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//Your logic when OK button is clicked
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id)
}
});
dialog = builder.create();
dialog.show();
}
Instead of Alert Dialog create a simple dialog with your custom layout like this
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dialog_lauout);
dialog.show();
Button button = (CheckBox) dialog.findViewById(R.id.button);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
I have a button inside a popupwindow that when clicked initializes an alertdialog with a list from which the user can choose from. I'm stuck trying to get the string value of the selected item from the list. I'm trying to get the item and then change the description text on the button to reflect the user's selection.
countryButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
final ArrayAdapter<CharSequence> countryAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.countries_array, android.R.layout.simple_spinner_item);
new AlertDialog.Builder(MakeQuestion.this)
.setTitle("Country")
.setAdapter(countryAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//String countryResult = countryList.get(which);
//countryButton.setText(countryResult);
dialog.dismiss();
}
}).create().show();
}
});
You have to use ArrayAdapter.getItem() method. And if it isn´t just a copy paste mistake, don´t forget the #Override annotation. But what do You mean with "missing reference error"?
countryButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
final ArrayAdapter<CharSequence> countryAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.countries_array, android.R.layout.simple_spinner_item);
new AlertDialog.Builder(MakeQuestion.this)
.setTitle("Country")
.setAdapter(countryAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String countryResult = countryAdapter.getItem(which);//use this getItem() method
countryButton.setText(countryResult);
dialog.dismiss();
}
}).create().show();
}
});
I have an android app that has two buttons. So basically what I am trying to do is when a user clicks the 'Share Button' on the page, an alert dialog box will appear that will prompt the user to enter their email address. Here is what I have so far. I've tried an EditView but it hasn't been working well for me.
Thanks in advance!
package com.colors;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
final Context context = this;
private Button button;
private Button shareButton;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
shareButton = (Button) findViewById(R.id.shareButton);
// add button listener for Welcome Message.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set the title of the Alert Dialog
alertDialogBuilder.setTitle("Welcome!");
// set dialog message
alertDialogBuilder
.setMessage("Program Description here...")
.setCancelable(false)
.setNegativeButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// if no is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
// Button listener for Share Button
shareButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set the title of the Alert Dialog
alertDialogBuilder.setTitle("Share");
// set dialog message
alertDialogBuilder
.setMessage("Would like to a user input here.")
.setCancelable(false)
.setPositiveButton("Send!",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// if no is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// if no is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
}
}
This may helpful to you.
shareButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder al1 = new Builder(
AgriListView.this);
al1.setMessage("Share Something");
al1.setPositiveButton("Share",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
final EditText input = new EditText(
AgriListView.this);
input.setSingleLine();
AlertDialog.Builder al = new Builder(
AgriListView.this);
al.setTitle("Enter New Value");
al.setView(input);
al.setCancelable(true);
al.setIcon(R.drawable.bt);
al.setPositiveButton(
"OK",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
int len = input
.length();
if (!(len == 0)) {
Toast.makeText(
AgriListView.this,
"Entered text is: "+input.getText()
,
Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(
getApplicationContext(),
"Enter Value Properly",
Toast.LENGTH_LONG)
.show();
}
}
});
al.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
dialog.cancel();
}
});
AlertDialog alert = al.create();
alert.show();
}
});
al1.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
dialog.cancel();
}
});
AlertDialog alert1 = al1.create();
alert1.show();
}
});
This code create dialog with Edittext value.
You could do something like this.
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Title");
alert.setMessage("Message");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText();
// Do something with value!
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
I'm trying without success to unselect all my checkbox picks
by pressing any button that in my java android program with this code
public void onListItemClick(ListView parent, View v, int position, long id)
{
parent.setItemChecked(position, parent.isItemChecked(position));
}
#Override
protected Dialog onCreateDialog(int id, Bundle args){
switch(id){
case 1:
return new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("This is a dialog with some simple text...")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(),"OK clicked!", Toast.LENGTH_SHORT).show();
}})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(),"Cancel clicked!", Toast.LENGTH_SHORT).show();
}
})
.setMultiChoiceItems(items, itemsChecked, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
Toast.makeText(getBaseContext(),items[which] + (isChecked ? " checked!":" unchecked!"),Toast.LENGTH_SHORT).show();
}
})
.create();
}
return(null);
}
how to select all and unselect all ?
Well, my best guess is to save a reference for all of them on a list, and go through all of them selecting or unselecting them all. Something like this.
Crete a reference to hold all your checkboxes
List<CheckBox> myCheckBoxes = new ArrayList<CheckBox>();
myCheckBoxes.add(cb1);
myCheckBoxes.add(cb2);
myCheckBoxes.add(cb3);
....
Create a method that will get the value you want to set on the check boxes and call it whenever you want.
:
private checkAll(boolean value) {
for(CheckBox cb : myCheckBoxes) {
cb.setChecked(value);
}
}
Create two buttons:
Button unselectAllButton = (Button) findViewById(R.id.unCheckButton);
Button selectAllButton = (Button) findViewById(R.id.checkButton);
unselectAllButton.setOnClickListener(setOnClickListener(new OnClickListener() {
public void onClick(View v) {
checkAll(false);
}
});
selectAllButton.setOnClickListener(setOnClickListener(new OnClickListener() {
public void onClick(View v) {
checkAll(true);
}
});