Acess AdapterView from Dialog - android

I have my ListActivity that when you tap on an item, it pops up a Dialog that ask the user for user and password. How can I get the selected position from the dialog?
Here's how I initialize the ListActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView listView = getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
showDialog(DIALOG_USER_PASSWORD);
}
});
}
The Dialog I pop up is a simple AlertDialog with 2 EditText which I inflate from an xml file
protected Dialog onCreateDialog(int id) {
switch (id) {
...
case DIALOG_USER_PASSWORD:
LayoutInflater factory = LayoutInflater.from(this);
final View dialogView = factory.inflate(R.layout.alert_dialog_text_entry, null);
return new AlertDialog.Builder(MyListActivity.this)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle(R.string.ask_user_password)
.setView(dialogView)
.setPositiveButton(R.string.ok_text, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String userName = ((EditText) findViewById(R.id.username_edit_alert_dialog))
.getText().toString();
String password = ((EditText) findViewById(R.id.password_edit_alert_dialog))
.getText().toString();
Credentials cred = new CredentialsL1(userName, password);
/* HERE IS WHERE i NEED THE SELECTED ITEM
mId IS THE OBJECT ASSOCIATED TO THE SELECTED POSITION */
mService.connect(mId, cred);
}
})
// Cancel button
.setNegativeButton(R.string.cancel_text,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
})
.create();
}
return null;
}
The only I've come up with is creating a new field "mId" and setting it when the user taps and using it when the user taps OK in the Dialog. Any more elegant idea?
Thanks

private int selectedPosition;
...
protected void onCreate(Bundle savedInstanceState) {
....
// inside the item listener...
selectedPosition = position;
showDialog(DIALOG_USER_PASSWORD);
/* HERE IS WHERE i NEED THE SELECTED ITEM
mId IS THE OBJECT ASSOCIATED TO THE SELECTED POSITION */
// just use selectedPosition var
Any more elegant idea?
It seems that you use a normal ListView (not a checkbox one)... so, it's fine to do it this way.

Related

Checkbox state in listview onItemLongClick

I have a listview in which when you select a row, it's checkbox becomes checked / unchecked. However, I have a onItemLongClick that displays a dialog.
Problem is when I long-click a row in the listview, it becomes checked and I don't want that to happen, I just need it to display a dialog. This is confusing me because the onItemClick is also called when I use onItemLongClick.
Here's the code for onItemClick:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckBox checkBox = (CheckBox)view.findViewById(R.id.checkmark);
TextView tv3 = (TextView)view.findViewById(R.id.tx_amount);
String shitts = listView.getItemAtPosition(position).toString();
HashMap<String, String> data = new HashMap<>();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
try {
checkBox.setChecked(!checkBox.isChecked());
String[] a = shitts.split(", ");
String[] sep = a[0].split("=");
String betamount = sep[1];
String[] sepx = a[2].split("=");
String betnumber = sepx[1];
String showbetnumber = betnumber.replaceAll("[;/:*?\"<>|&{}']","");
if(checkBox.isChecked()){
hash.put(showbetnumber,tv3.getText().toString());
}else {
tv3.setText(betamount);
checked.removeAll(Collections.singletonList(position));
hash.remove(showbetnumber,tv3.getText().toString());
}
}catch (Exception e){
}
}
});
and here's the code for onItemLongClick
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
TextView txAmt = view.findViewById(R.id.tx_amount);
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Enter Amount:");
final EditText input = new EditText(MainActivity.this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setRawInputType(Configuration.KEYBOARD_12KEY);
alert.setView(input);
alert.setPositiveButton("enter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String x = input.getText().toString();
txAmt.setText(x);
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Put actions for CANCEL button here, or leave in blank
}
});
alert.show();
return false;
}
});
Any help is appreciated!
Create a boolean isLongClick and set it to false.
onItemLongClick(), set isLongClick to true.
On your dialog, set isLongClick to false again when any button is clicked or if the dialog was dismissed.
Finally, wrap all your code inside onItemClick() in:
if (!isLongClick) {
// onItemClick() code
}
The source of this solution

I want to get the selected value from List view in alert dialog

I have ArrayList of object (citiesInSpinner) each object have two value(Id, Name)
I have already get it in alert dialog
I use this function to alert dialog:
public void test()
{
FillSpinner();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(SearchFligtsActivity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.custom, null);
alertDialog.setView(convertView);
alertDialog.setTitle("Select City");
ListView lv = (ListView) convertView.findViewById(R.id.listView1);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,citiesInSpinner);
lv.setAdapter(adapter);
/* alertDialog.setItems(citiesInSpinner, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
/////
}
});*/
alertDialog.show();
/**/
}
now I want to make something to get the ((ID)) of item (I mean the Id of City)
I tried to do that but I failed...
any help Please !!
and thank you
Simply use
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
City city = citiesInSpinner.get(position)
//get your id -> city.Id
}
});

AlertDialog - do not dismiss on item click

OK so I am creating an ArrayAdapter and using it in my Alert Dialog because I don't want to show the default radio buttons on SingleItemSelection dialog.
Instead I want to change the background of the item that is selected, and then when the user presses the positive button I will perform the action related to the item that has been selected.
private void showAlertDialog()
{
final String[] options = getResources().getStringArray(R.array.dialog_options);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, options);
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("My Dialog");
dialogBuilder.setAdapter(adapter, new OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "item clicked at index " + which, Toast.LENGTH_LONG).show();
// Here I need to change the background color of the item selected and prevent the dialog from being dismissed
}
});
//String strOkay = getString(R.string.okay);
dialogBuilder.setPositiveButton("OK", null); // TODO
dialogBuilder.setNegativeButton("Cancel", null); // nothing simply dismiss
AlertDialog dialog = dialogBuilder.create();
dialog.show();
}
There are two problems I'm trying to tackle.
How do I prevent the dialog from being dismissed when the user clicks on an item
How do I change the background of the item that has been selected when the user clicks on it
To prevent dialog from dismissing on item click you can use AdapterView.OnItemClickListener instead of DialogInterface.OnClickListener.
Like this:
dialogBuilder.setAdapter(adapter, null);
...
AlertDialog dialog = dialogBuilder.create();
alertDialog.getListView().setOnItemClickListener(
new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// do your stuff here
}
});
You can set custom ListView as content of AlertDialog and set OnItemClickListener
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String[] items = ...;
ListView list = new ListView(this);
list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, items));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int pos, long id) {
...
}
});
builder.setView(list);
and then save reference to dialog
mDialog = builder.show();
in order to dismiss it if necessary
mDialog.dismiss();
How do I prevent the dialog from being dismissed when the user clicks on an item
How do I change the background of the item that has been selected when the user clicks on it
Here is example
public class MainActivity extends AppCompatActivity {
private static final String listFragmentTag = "listFragmentTag";
private static final String data[] = {"one", "two", "three", "four"};
public MainActivity() {
super();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btnClick(View v) {
ListFragment lf = new ListFragment();
lf.show(getSupportFragmentManager(), listFragmentTag);
}
public static class ListFragment extends DialogFragment {
#Override #NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
adb.setIcon(android.R.drawable.ic_dialog_info)
.setTitle("List")
.setItems(data, null)
.setPositiveButton("OK", null); // pass your onClickListener instead of null
// to keep dialog open after click on item
AlertDialog ad = adb.create();
ad.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
private int colorOrg = 0x00000000;
private int colorSelected = 0xFF00FF00;
private View previousView;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// restoring color of previous view
if(previousView != null) {
previousView.setBackgroundColor(colorOrg);
}
// changing items's BG color
view.setBackgroundColor(colorSelected);
previousView = view;
}
});
return ad;
}
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
}
}
}
You can use setCanceledOnTouchOutside(false) or setCanceleable(false).
Set selector for the root element tag of the dialog layout xml.

Highlight selected Spinner Item

I have implemented Custom Spinner using Button following wildnove's answer. Everything works fine, but I am not able to display the highlighted radio button for the selected button.
Below is the code.
((Button) findViewById(R.id.btnSpinnerPlanets)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// How to highlight Radio button of a selected Item???
final String[] items = view.getResources().getStringArray(R.array.planets__entries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MyFormActivity.this, android.R.layout.simple_spinner_dropdown_item, items);
new AlertDialog.Builder(MyFormActivity.this).setTitle("the prompt").setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((Button) findViewById(R.id.btnSpinnerPlanets)).setText(items[which]);
dialog.dismiss();
}
}).create().show();
}
});
Can somebody help me how to highlight selected Item's Radio button ...
Unfortunately this behavior is not natively implemented in Spinner component, however, you can always create your own BaseAdapter to show whatever you need weather is in the spinner it self or in the dropdown like this:
private class ExampleAdapter extends BaseAdapter{
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//Here is where you actually get the chance to return whatever you want in the spinner component (the single bar with the arrow)
return yourCommonView;
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
//Here is where you get the chance to return whatever you want in the dropdown menu so here you should validate what's the currently selected element and return an image accordingly...
return yourSelectedView;
}
}
The important method here is, getDropDownView that is the one that gives you the chance to return an element with a checked CheckBox, or any mark you want to use, of course you have to create your own layout and validate if the element currently created need to be marked or not...
Regards!
The problem with this code is that you are creating the Spinner each time the Button is clicked. Try the following code:
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
AlertDialog.Builder builder;
switch(id) {
case 1:
Button b=((Button) findViewById(R.id.btnSpinnerPlanets));
builder = new AlertDialog.Builder(MyFormActivity.this).setTitle("the prompt").setAdapter(get_the_adapter(b), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
b.setText(b.getResources().getStringArray(R.array.planets__entries)[which]);
dismissDialog(1);
}
})
dialog = builder.create();
break;
default:
dialog = null;
}
return dialog;
}
}
public ArrayAdapter<String> get_the_Adapter(Button view){
String[] items = view.getResources().getStringArray(R.array.planets__entries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MyFormActivity.this, android.R.layout.simple_spinner_dropdown_item, items);
return adapter;
}
And for the Button's onClick():
((Button) findViewById(R.id.btnSpinnerPlanets)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog(1);
}
});

Access controls within custom alert dialog in android

When displaying custom dialog box which is showing textView and EditView. How can i access these elements within dialog. Below is the code which is giving error.
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
return new AlertDialog.Builder(AlertDialogSamples.this)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle(R.string.alert_dialog_text_entry)
.setView(textEntryView)
.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
string = uetd.getText().toString() + ":" + petd.getText().toString(); /////producing error
}
})
.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked cancel so do some stuff */
}
})
.create();
public class listdemo extends ListActivity {
/** Called when the activity is first created. */
private static final int DIALOG_TEXT_ENTRY = 7;
EditText uetd;
EditText petd;
SharedPreferences.Editor editor;
String string;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
uetd=(EditText)findViewById(R.id.username_edit);
petd=(EditText)findViewById(R.id.password_edit);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
showDialog(DIALOG_TEXT_ENTRY);
}
});
}
}
Instead of returning the dialog immedately with return new AlertDialog.builder....and so on....you should save an instance of the dialog by creating a class variable just like this
AlertDialog dialog;
Then you can easily access the views of the dialog within the callback of the dialog:
dialog.findViewById(R.id.username_edit);
You have to do this because when creating the callback it is in a way constructing a new class in memory so when you call findViewById() directly it can't find the activity
try this code
uetd=(EditText) textEntryView.findViewById(R.id.username_edit);
after following line in your code
final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);

Categories

Resources