Multiple choice AlertDialog with custom Adapter - android

I am trying to create a AlertDialog with multiple choice option. I have tried with the setMultiChoiceItems but what i have is a ArrayList<Category> and not a CharSequence so i tried with the adapter.
The problem with setAdapter is that when i select one item it closes the dialog window. And what i want is to select the items and then hit the OK button to see what items where selected.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
ArrayAdapter<Category> catsAdapter = new ArrayAdapter<Category>(this, android.R.layout.select_dialog_multichoice,this.categories);
builder.setAdapter(catsAdapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
}
});
builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//do something
}
});;
AlertDialog alert = builder.create();
alert.show();

Unfortunately, there doesn't seem to be an easy way to toggle on AlertDialog's multichoicemode without calling setMultiChoiceItems().
However, you can set an adapter, then turn on multichoice mode in the contained ListView itself.
final AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setTitle("Title")
.setAdapter(yourAdapter, null)
.setPositiveButton(getResources().getString(R.string.positive), null)
.setNegativeButton(getResources().getString(android.R.string.cancel), null)
.create();
dialog.getListView().setItemsCanFocus(false);
dialog.getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
dialog.getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Manage selected items here
System.out.println("clicked" + position);
CheckedTextView textView = (CheckedTextView) view;
if(textView.isChecked()) {
} else {
}
}
});
dialog.show();

this will stop ur dialog from disappearing after one selection.
AlertDialog alertDialog = builder.create();
ListView listView = alertDialog.getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
}
});
To get which items are selected , you need to plan your adapter accordingly.

see below code it may help you. i used this in my app.
public static ArrayList<String> Party_list_new = new ArrayList<String>();
ArrayList<String> party_multi_cheked = new ArrayList<String>();
public void show_alert() {
final Dialog dia = new Dialog(this);
dia.setContentView(R.layout.alert_);
dia.setTitle("Select File to import");
dia.setCancelable(true);
final ListView list_alert = (ListView) dia
.findViewById(R.id.alert_list);
list_alert.setAdapter(new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_multiple_choice,
Party_list_new));
list_alert.setItemsCanFocus(false);
list_alert.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list_alert.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
}
});
Button btn = (Button) dia.findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SparseBooleanArray positions = list_alert
.getCheckedItemPositions();
int j = 0;
for (int k = 0; k < Party_list_new.size(); k++) {
if (positions.get(k)) {
party_multi_cheked.add("" + k);
}
}
dia.dismiss();
}
});
dia.show();
}
alert_list.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Party" />
<ListView
android:id="#+id/alert_list"
android:layout_width="match_parent" android:padding="5dp"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
make it right if it is correct.

Related

How to get a ListView's elements in a AlertDialog

I am relatively new to android and I am stuck on this problem. I created a button which launches a Dialog. The AlertDialog (to be specific) then programatically create a listView and assign an adapter to it. Now the user can click on some of the elements and the textView elements in the ListView become red. I then store the elements that were clicked. Now, when I create a dialog again, the same texts that were clicked become white.
So my question is, how do I access the listView's elements beforehand so I can alter the colour of the items that were previously clicked.
this is the java code:
private void populateListView(String[] els) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.single_listview_item,R.id.txtitem, els);
list = new ListView(this);
list.setAdapter(adapter);
list.setOnItemClickListener( new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
ViewGroup vg=(ViewGroup)view;
TextView txt=(TextView)vg.findViewById(R.id.txtitem);
if(!currentList.isSelected(position)) {
txt.setBackgroundResource(R.color.redPastel);
currentList.select(position);
}
else{
txt.setBackgroundResource(R.color.white);
currentList.unselect(position);
}
}
});
}
//the listener for the button
public void showDialogListView(View view){
String [] selection = {};
Button buttonUsed = null;
switch (view.getId()){
case R.id.cuisineButton:
selection = cuisines.getArray();
currentList = cuisines;
buttonUsed = (Button) findViewById(R.id.cuisineButton);
break;
case R.id.mealTimeButton:
selection = times.getArray();
currentList = times;
buttonUsed = (Button) findViewById(R.id.mealTimeButton);
break;
}
populateListView(selection);
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setCancelable(true);
final Button finalButtonUsed = buttonUsed;
builder.setPositiveButton("Select",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finalButtonUsed.setText(currentList.getSelectionText());
}
});
builder.setNegativeButton("Cancel",null);
builder.setView(list);
AlertDialog dialog=builder.create();
dialog.show();
}
}
this is the layout of the single element XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtitem"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:textSize="25sp"
android:gravity="center"
/>
</LinearLayout>
You can get listView item like as
lv_view_task.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,final int arg2,
long arg3) {
final View selectedView v = arg1 ; // Save selected view in final variable**
AlertDialog.Builder alert=new AlertDialog.Builder(ViewTask.this);
alert.setTitle("title stackoverflow");
alert.setIcon(R.drawable.ic_launcher);
alert.setPositiveButton("Fix",new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String str=lv_view_task.getItemAtPosition(arg2).toString();
Toast.makeText(getApplicationContext(), str,Toast.LENGTH_LONG).show();
//Access view object v here
TextView label=(TextView) v.findViewById(R.id.label);
String xyz = label.getText();
}
});

Keyboard not showing above Custom AlertDialog when user clicks on EditText

I'd like to show keyboard to the user when I my alertdialog ABOVE it, I've already tried with
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
however, keyboard gets displayed UNDER the dialog.
I've already set my activity in manifest like this:
<activity
android:name=".ActivityMain"
android:label="#string/app_name"
android:windowSoftInputMode="adjustResize"
/>
Here's the code I used to generate the dialog
public void createConstDialog(String[] textstring) {
AlertDialog.Builder builder =
new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.dialog_editconstantformula, null);
builder.setView(dialogView);
builder.setTitle("Edit Values");
builder.setCancelable(false);
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_view_calculator_formula, R.id.constid, textstring);
lv = (ListView) dialogView.findViewById(R.id.list_view1);
final MyListAdapter myListAdapter = new MyListAdapter();
lv.setAdapter(myListAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long viewId) {
mConstid = (TextView) view.findViewById(R.id.constid);
mConstid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("touched", "" + position);
}
});
mConstvalue = (EditText) view.findViewById(R.id.constvaluez);
mConstvalue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("touched", "" + position);
}
});
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < lv.getCount(); i++) {
View wantedView = lv.getChildAt(i);
mConstvalue = (EditText) wantedView.findViewById(R.id.constvaluez);
String letter = lv.getItemAtPosition(i).toString();
String value = mConstvalue.getText().toString();
Log.d("touched", (letter + "valore: " + mConstvalue.getText().toString()));
mFormulaEditText.setText(mFormulaEditText.getText().toString().replaceAll(letter, value));
}
dialog.dismiss();
}
});
builder.show();
}
R.layout.dialog_editconstantformula
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ListView
android:id="#+id/list_view1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:dividerHeight="1dp"
android:padding="10dp" >
</ListView>
</LinearLayout>
But with a similar code in a different activity, (from AlertDialog.builder to (false);), I get Keyboard showing on click on an edittext. I also tried to remove my listview from the edittext, however nothing happens.
I had the same problem, you should replace android:windowSoftInputMode="adjustResize" with "android:windowSoftInputMode="stateVisible"

Grid View setOnItemClickListener() not working for custom grid view

I have a button and when I click that button my first custom grid view pops up as dialogue. When I click an item my second custom grid view pops up dismissing my first custom grid view. Now the problem is here, when I click an item in my second custom grid view nothing happens. My setOnItemClickListener() is not working there.I couldn't able to trace my problem where I have done wrong.
Showing my first grid view `
public void outletList() {
dialogOutlet = new Dialog(SelectCategory.this);
dialogOutlet.setContentView(R.layout.outlet_dialogue_grid);
dialogOutlet.setTitle("Select Outlet");
final GridView lv = (GridView) dialogOutlet.findViewById(R.id.gridOutletView);
oa = new OutletAdapter(this, ParseData.OutletList);
lv.setAdapter(oa);
outletFlag = 1;
lv.setOnItemClickListener(this);
dialogOutlet.show();
dialogOutlet.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
outletFlag = 0;
}
});
}`
Showing second grid view `
public void billList() {
dialogueBill = new Dialog(SelectCategory.this);
dialogueBill.setContentView(R.layout.bill_dialogue_grid);
dialogueBill.setTitle("Select Bill");
final GridView bv = (GridView) dialogueBill.findViewById(R.id.gridBillView);
ba = new BillAdapter(this, ParseData.BillList);
bv.findFocus();
bv.setAdapter(ba);
bv.setFocusableInTouchMode(true);
bv.requestFocus();
bv.setClickable(true);
bv.setFocusable(true);
System.out.println("focusable "+bv.isFocusableInTouchMode());
System.out.println("focusable "+bv.findFocus());
System.out.println("Outlet Flag Bill List>>>>>>"+outletFlag);
bv.setOnItemClickListener(this);
dialogueBill.show();
dialogueBill.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
outletFlag = 0;
}
});
}`
On Item Click
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
System.out.println("Outlet Flag inside Item Click>>>>>>"+outletFlag);
if(outletFlag!=1){
HashMap<String, String> out = BillAdapter.billData.get(pos);
String sel_bill = out.get(ParseData.KEY_BILL_NO);
System.out.println("Selected Bill>>>>>>"+sel_bill);
selected_bill = sel_bill;
Intent iii = new Intent(SelectCategory.this, FBHome.class);
startActivity(iii);
}
else{
HashMap<String, String> out = OutletAdapter.outletData.get(pos);
String sel_name = out.get(ParseData.KEY_NAME);
String sel_code = out.get(ParseData.KEY_CODE);
out_pos = pos;
selected_outlet = sel_code;
selected_outlet_name = sel_name;
dialogOutlet.dismiss();
outletFlag = 0;
new GetBillDetails().execute();
}
}
Thanks in advance :)
In your Gridview Layout if you are using Clickable Widgets like Button or an ImageButton Change it and try.
That is android does not recognize click events inside the Gridadpater views, so if you change that everything should work fine
You could try
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#android:color/darker_gray"
android:layout_width="90dp"
android:layout_height="90dp"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/bt_grid"
android:layout_width="wrap_content"
android:textColor="#android:color/white"
android:layout_height="wrap_content" />
</LinearLayout>
Try using Alert Dialog
private void showGridDialog() {
// Prepare grid view
final GridView bv = (GridView)
dialogueBill.findViewById(R.id.gridBillView);
ba = new BillAdapter(this, ParseData.BillList);
bv.findFocus();
bv.setAdapter(ba);
bv.setFocusableInTouchMode(true);
bv.requestFocus();
bv.setClickable(true);
bv.setFocusable(true);
bv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// do something here
}
});
// Set grid view to alertDialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(bv);
builder.setTitle("Goto");
builder.show();
}

AlertDialog box containing spinner and edittext returning a nullpointer when called

I have a dialog box that works perfectly well when i use just the spinner, but returns a null pointer when i try to fetch a value from an edit Text to be used for calculation in the OK button.
below is my deliberations for your consideration
//the alert box
public boolean dialogValuessP1() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
Arena.this);
alertDialogBuilder.setTitle("Connecting Options");
LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View dialogView = li.inflate(R.layout.option, null);
EditText connectionNumber = (EditText)findViewById(R.id.txtConnectedBy);
connectedV = Integer.parseInt(connectionNumber.getText().toString());
spinnercategory = (Spinner) dialogView.findViewById(R.id.viewSpin);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.category, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnercategory.setAdapter(adapter);
spinnercategory.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
ConnectBY = spinnercategory.getItemAtPosition(arg2).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
alertDialogBuilder.setView(dialogView);
alertDialogBuilder.setPositiveButton("Connect",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (ConnectBY == "Single Score") {
scoreV = 1 * connectedV;
} else if (ConnectBY == "Double Score") {
scoreV = 2 * connectedV;
} else if (ConnectBY == "Tripple Score") {
scoreV = 3 * connectedV;
}
alert = true;
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the alert box and put a Toast to the user
dialog.cancel();
Toast.makeText(getApplicationContext(),
"Please choose Connection Pattern",
Toast.LENGTH_LONG).show();
// Arena.this.finish(); used to close the game
alert = false;
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
return alert;
}
//the option.xml is the Xml file used
<?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="fill_parent"
android:orientation="vertical"
android:paddingLeft="10dip" >
<Spinner
android:id="#+id/viewSpin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#array/category" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/connectwith" />
<EditText
android:id="#+id/txtConnectedBy"
android:layout_width="76dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
</LinearLayout>
Since the edittext is inside the alert dialog
try using
EditText connectionNumber =(EditText) dialogView .findViewById(R.id.txtConnectedBy);
and to retrive the value use
String edittextValue=connectionNumber.getText().toString()
I think you can achieve this functionality with a custom dialog functionality
final Dialog dialog = new Dialog(CustomDialog.this);
// Include dialog.xml file
dialog.setContentView(R.layout.dialog);
// Set dialog title
dialog.setTitle("Custom Dialog");
// set values for custom dialog components - text, image and button
EdittText text = (EdittText ) dialog.findViewById(R.id.textDialog);
Spinner spinimage = (Spinner) dialog.findViewById(R.id.spinner);
//spinner details here
dialog.show();
Button ok= (Button) dialog.findViewById(R.id.ok);
ok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Close dialog
dialog.dismiss();
String text = text.getText().toString();
//do something with the edittext value
}
});
please make a try and share your view
Thanks for the suggestions, i made the following changes to the code and was able to use both an edittext and a spinner in the same alertdialog
public boolean dialogValuessP1() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setTitle("Connecting Options");
LayoutInflater li = LayoutInflater.from(context);
final View dialogView = li.inflate(R.layout.option, null);
final EditText input = (EditText) dialogView
.findViewById(R.id.txtConnectedBy);
spinnercategory = (Spinner) dialogView.findViewById(R.id.viewSpin);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.category, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnercategory.setAdapter(adapter);
spinnercategory.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
position = arg2 + 1;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
alertDialogBuilder.setView(dialogView);
alertDialogBuilder.setPositiveButton("Connect",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
edittextValue = input.getText().toString();
connectedV = Integer.parseInt(edittextValue);
scoreV = position * connectedV;
playNext();
alert = true;
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the alert box and put a Toast to the user
dialog.cancel();
Toast.makeText(getBaseContext(),
"It is not your turn to Play",
Toast.LENGTH_LONG).show();
alert = false;
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
return true;
}

listview open alert dialog depending on choice android

Im desperately trying to get my listView to open an alert dialog or a normal dialog that is filled with information. I cant seem to get it to work. I want it to display different information aswell depending on which item on the list is clicked
public class learn_tab1 extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item,
BASICLIST));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
AlertDialog dialog = new AlertDialog.Builder(this).create();
dialog.setCancelable(false);
dialog.setTitle("Instructions");
dialog.setIcon(R.drawable.bone_icon);
dialog.setMessage("test");
dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
}
});
dialog.show();
}
}
});
}
Try new AlertDialog.Builder(learn_tab1.this).create(); instead of new AlertDialog.Builder(this).create().
I'm wondering how it ever get complied....
EDIT
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = (String)parent.getItemAtPosition(position);
// ...
dialog.setMessage(item);
// ...
}

Categories

Resources