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.
Related
When the user clicks the item of list View a alert Dialog box will be displayed to the user with options like "view","delete" or "update"
the list view item. Clicking on the list view item for the first time displays the alert Dialog with options but when i click another list View item or the same list View item the second time the app crashes.Thanks in advance.
Error :java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
//The main list displayed when the user log in successfully
ListView = (ListView) findViewById(R.id.list);
ListView2 = new ListView(this); //List to be displayed in the alert Dailog box
ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
long i = ListView.getItemIdAtPosition(position);
showAlertDailog();//The dialog box method
}
});
if(mCursorAdapter == null) //To check if the list is empty
{
TextView emptyTextView = (TextView) findViewById(R.id.empty);
emptyTextView.setText("No Notes");
ListView.setEmptyView(emptyTextView);
}else {
mCursorAdapter = new DataCursorAdapter(this, null);
ListView.setAdapter(mCursorAdapter);
}
public void showAlertDailog()
{
String [] items = {"View","Delete","Update"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.item_todo_2,R.id.textView4,items);
ListView2.setAdapter(adapter);
final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(HomeActivity.this);
builder.setView(ListView2)
.setCancelable(false)
.setPositiveButton("Close",null);
android.app.AlertDialog alertDialog = builder.create();
alertDialog.show();
}
ArrayList<String> arrayList = new ArrayList<String>();
CharSequence[] animals = arrayList.toArray(new String[arrayList.size()]);
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setItems(animals, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String selectedText = animals[item].toString();
}
});
AlertDialog alertDialogObject = dialogBuilder.create();
alertDialogObject.show();
This is simple way to display list inside alert dialog, where in arraylist just add string whatever you have to display inside alert dialog list.
It is exactly what you need
public class MainActivity extends Activity implements OnClickListener {
private Button mDoneButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDoneButton = (Button) findViewById(R.id.done_button);
mDoneButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
final CharSequence[] items = {
"Rajesh", "Mahesh", "Vijayakumar"
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Make your selection");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// Do something with the selection
mDoneButton.setText(items[item]);
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
http://rajeshvijayakumar.blogspot.in/2013/04/alert-dialog-dialog-with-item-list.html
OUTPUT
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String[] listItems = { "Colour", "Font Size", };
if (listItems[position].equals("Font Size")) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
Settings.this );
// set title
alertDialogBuilder.setTitle("Choose Font Size");
// set dialog message
alertDialogBuilder
.setMessage("Click yes to exit!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
}
});
public void showAlertDailog(Context context) {
ListView listView=new ListView(context);
yourLayout.LayoutParams params= yourLayout.LayoutParams(Yourlayout.LayoutParams.MATCH_PARENT,Yourlayout.LayoutPa
rams.MATCH_PARENT);
listview.setLayoutParams(params);
String [] items = {"View","Delete","Update"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,items);
listView.setAdapter(adapter);
final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context);
builder.setView(listView)
.setCancelable(false)
.setPositiveButton("Close",(dialog,something)->{dialog.dismiss()});
android.app.AlertDialog alertDialog = builder.create();
alertDialog.show();
}
I have been trying to get this library:
https://github.com/bauerca/drag-sort-listview/
to work inside an AlertDialog. But I have has no success so far. Everything looks perfect but the drag and drop does not happen.
Any suggestion it can be done? If there is no way to do this inside a AlertDialog, is there a way to do this without using intents?
Here is my code:
public class FolderSorter
{
Context parent;
ArrayList<String> lists;
ArrayAdapter<String> adapter;
public FolderSorter(Context context)
{
this.parent = context;
lists = new ArrayList<String>();
adapter = new ArrayAdapter<String>(parent, R.layout.list_item1,
R.id.text1);
}
public void setList(List<String> mlist)
{
this.lists.addAll(mlist);
}
public void doSort()
{
LayoutInflater factory = LayoutInflater.from(parent);
final View lview = factory.inflate(R.layout.sort_folders, null);
AlertDialog.Builder builder = new AlertDialog.Builder(parent);
builder.setTitle("Sort Folders");
builder.setView(lview);
// ListView list = (ListView) lview.findViewById(R.id.listView1);
DragSortListView list2 = (DragSortListView) lview
.findViewById(R.id.dragSortListView1);
adapter.addAll(lists);
// list.setAdapter(adapter);
list2.setAdapter(adapter);
// TODO: set buttons OK and CANCEL
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int id)
{
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int id)
{
}
});
final Dialog dialog = builder.create();
dialog.show();
}
private DragSortListView.DropListener onDrop = new DragSortListView.DropListener()
{
#Override
public void drop(int from, int to)
{
String item = adapter.getItem(from);
adapter.remove(item);
adapter.insert(item, to);
}
};
private DragSortListView.RemoveListener onRemove = new DragSortListView.RemoveListener()
{
#Override
public void remove(int which)
{
adapter.remove(adapter.getItem(which));
}
};
}
I had a similar problem when using the DragSortListView inside a dialog fragment - turned out this only happened when the soft keyboard was visible when the fragment was being displayed. I'm not sure what the exact issue is, but I think something is either interfering with the focus or touch events the DragSortListView uses.
As a work around I hide the softkeyboard before displaying the fragment, this appears to solve the issue for now - see the below answer for the code on how to do this:
https://stackoverflow.com/a/7696791/1062909
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);
// ...
}
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.
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);