Android: How to set the selection in a single choice AlertDialog? - android

I created a single choice AlertDialog with "Apply" and "Cancel" buttons. When the user presses "Cancel", I would like to set the selected item back to what it was when the dialog was first shown (I have the value stored already).
I know how to set the selected item when the dialog is first created in setSingleChoiceItems() but is there a way to set it again later?
I would like to be compatible with API level 7, so I'd rather not use onPrepareDialog().

Well, nobody could find a solution to my problem, so I settled for a dialog which doesn't use buttons. When the user presses an item in the list, that selection is applied and the dialog is dismissed. No need to remember previous choices or support cancelling.

You can create your dialog on the spot rather than going through showDialog and onCreateDialog. This way its always using the current selection we give to setSingleChoiceItems.
//where we display the dialog
showDialog(MYDIALOG);
AlertDialog.Builder builder = new Builder(this);
String[] choices = {"A","B","C"};
builder.setSingleChoiceItems(choices,current_choice,null);
builder.setPositiveButton("Select",null);
builder.setNegativeButton("Cancel",null);
builder.show();
...
protected Dialog onCreatDialog(int id) {
if (id==MYDIALOG) {
AlertDialog.Builder builder = new Builder(this);
String[] choices = {"A","B","C"};
builder.setSingleChoiceItems(choices,current_choice,null);
builder.setPositiveButton("Select",null);
builder.setNegativeButton("Cancel",null);
return builder.show();
}
return null;
}

In Altert Dialog For creating single choice have you used single choice list view or radio group?
If You have used Single Choice Listviwe then no need to worry.
IF you have used Radio Group then you have to keep track of selected Radio Button Using Global Varialbe in your activity.

What you want to do when user click on cancel.
when user click on cancel than do you want to remove selected item from list if yes then you have to do the following.
In Your listitemseleted listener
alb.setSingleChoiceItems(items, 0, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/* which argument is the position of the item in
array items you have to remove this item from items array
Make your items array global variable.since in java array are
immutable you have to use arraylist.Arraylist can be converted
to array.*/
}
});
hope this will help if any question feel free to ask.

Related

How do I show a dialog fragment over another app when sharing from that app?

I'm making an app which other apps share/send to. When this happens, I want to show a dialog over the top of the existing app, the user chooses one of the options, then my app does something invisible and the user pops back to the original app - much like when you share something to Google+ but have multiple accounts set up, and it lets you choose which account to use.
Currently the activity (SendToActivity) which is started on the SEND intent is essentially a normal activity, made invisible with android:theme="#android:style/Theme.Translucent.NoTitleBar". Am I going down the right path by using a DialogFragment, and changing SendToActivity to extend FragmentActivity instead of AppCompatActivity?
I ended up using an AlertDialog, with an ArrayAdapter to make the list:
AlertDialog.Builder builder = new AlertDialog.Builder(SendToActivity.this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
for(String[] player: players){
adapter.add(player[0]);
}
builder.setTitle("Which Player?");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
sendToPlayer(item);
}
});
AlertDialog dialog = builder.create();
dialog.show();

How to display a (modal) dialog at the very start of the app?

At the start of my Android app the user is required to choose from a list of alternatives. Here is why.
Let's assume I have a long list of items, and each item belongs to exactly one category. Each user is only interested in one specific category. Thus, when the app is started and the SharedPreferences don't contain any information about the selected category, a modal dialog should be displayed - here the user has to choose his or her category of interest. After having selected a category, only the items of that category are displayed.
So far, I tried to implement this behavior in the Activity's onCreate() method, which doesn't work obviously. The dialog is not shown or at least not long enough so that I could see it.
To be honest, I didn't expect the code to work by calling it from onCreate(). However, I was unable to find a suitable event handler in the Activity from where I could trigger the dialog.
Where should this dialog be triggered from in order to ensure the selection of a category (before any other data is loaded)?
Thanks in advance.
Here's the code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
setContentView(R.layout.activity_item_list);
...
ensureCategorySelected();
}
where the relevant method is
private void ensureCategorySelected() {
String chosenCategory = getCategoryFromSharedPreferences();
if (chosenCategory != null) {
final CharSequence[] items = getCategories();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose category");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// handle the selection of the category
}
});
AlertDialog alert = builder.show();
}
}
You have a logic problem there. You want to show the dialog when there are still no preferences saved, and you are showing it when there are preferences saved. Change it to chosenCategory == null and it should work.
And why didn't you expect the code to work in onCreate()? I don't see a problem opening a dialog there.
Edit: I'm not quite sure if onCreate() is the correct place to show the dialog. Try putting ensureCategorySelected() in onStart() instead of onCreate().
You could also consider implementing an activity for this, which you could start with startActivityForResult().

In Android how do you get an alert dialog to add an item to a list if the user presses yes and viceversa

I am developing a simple Restaurant application in Android, I used menus and inflated submenu items corresponding to each menu item, I wanted to know a way of how to add the name of the dish to list only if the user selects yes in the alert dialog and viceversa.
Here is my code
public boolean onOptionsItemSelected(MenuItem m)
{
super.onOptionsItemSelected(m);
switch(m.getItemId())
{
case R.id.Chicken_Biryani:
selectedItem.add(m.getTitle().toString());
cost.add(150);
Toast.makeText(getApplicationContext(),"Hyderabadi special: Chicken biryani costs 150 Rs"+selectedItem, Toast.LENGTH_LONG).show();
showDialog(ALERT_DIALOG);
break;
case R.id.Butter_Chicken:
selectedItem.add(m.getTitle().toString());
cost.add(150);
Toast.makeText(getApplicationContext(),"Now with Punjabi Tadka: Butter Chicken costs 150 Rs", Toast.LENGTH_LONG).show();
showDialog(ALERT_DIALOG);
break;
........
public Dialog onCreateDialog(int id) {
switch(id)
{
case ALERT_DIALOG:
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setTitle("Buy Items");
ab.setMessage(" You have added the item to your cart ");
ab.setIcon(R.drawable.shopcart);
ab.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
Toast.makeText(getApplicationContext(),"Item added to cart your cart contains "+selectedItem.size()+" Items", Toast.LENGTH_LONG).show();
}});
Dialog ad = ab.create();
return ad;
}
return null;
}
// how do i pass the data of the onOptionsItemSelected to the list only if the user selects yes in the alertdiaolog
Please see this question for more information. It links to another answer which talks about how and when you can use notifyDataSetChanged.
I think in your AlertDialog you would want an "Add" button and a "Cancel" button to cancel adding it to the cart. Upon clicking add, your would insert the item into the users cart. To add another button to your AlertDialog you would use ab.setNegativeButton(...) just as you did with the setPositiveButton. This is just my take on it, am I correctly understanding your use of onCreateDialog - or is it used only to tell the user it has been added?
Please see this question for more specific help on how to implement within an AlertDialog.

Android opening context menu after button click

I want to open context menu when I click a button, but also I have to know which list item is focused when I click the button. Do you know how to do that? What code should be in onclick method?
I was looking for the same, and found that instead of context menu, you should use Dialogs
final CharSequence[] items = {"Red", "Green", "Blue"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog
If you really want to do it for whatever reason... (in my case, out of laziness)
During onCreate of your activity or somewhere before your user can touch the button, do registerForContextMenuon that button. Then in the actual button onClick handler, call openContextMenu(View).
For example, I have a button declared in xml like
<Button
android:id="#+id/btn_help"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onHelp"
android:text="#string/help_btn_text" />
in my onCreate
registerForContextMenu(findViewById(R.id.btn_help));
and in onHelp function
public void onHelp(View v) {
openContextMenu(v);
}
this works because the View v is the same as the view registered for context menu.
First thing, you should register the view by calling registerForContextMenu(View view). Second, override the onCreateContextMenu() to add the menus and lastly, override the onContextItemSelected() to put logic on each menu.
First of all, you should know why you should use ContextMenu. The functionality of ContextMenu of a View is similar to the right-click menu on a PC, which means the "available operations" on some item.
According to your description, I think what you actually need is a customized Dialog with a list, which is displayed when clicking the Button and is also able to get the focused item of your ListView. Then you can save the registration of ContextMenu for some View that really needs the menu:)

Android: Alert Dialog with CheckedTextView

Ok guys..I have a problem...
I need to create a dialog with 3 CheckedTextView. And when i open a dialog, second item should be checked...How to do that ? Code ...
#Override
protected Dialog onCreateDialog (int id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Something..");
builder.setInverseBackgroundForced(true);
ListView listView = new ListView(this);
listView .setAdapter(new ArrayAdapter(Settings.this, android.R.layout.select_dialog_multichoice, new String {a ,b, c}));
builder.setView(listView );
http://developer.android.com/guide/topics/ui/dialogs.html
check adding check boxes and radio buttons ,
One method would be ,
Have a flag through which you can decide
which to check next time when you popup the dialog and set the radio button in code ,
get radio button view and use toggle()
Check radio buttons and checkbox,
http://developer.android.com/resources/tutorials/views/hello-formstuff.html
Another method would be to use CheckBoxPreference.
Hope it helps.
Try this listView.getAdapter().getItem(1);. if your 2nd list item is check box, then set it checked by setChecked(true);

Categories

Resources