Show list view in a popup window - Android - android

I'm working on a project in Android and I have a problem.
I have an activity which includes three buttons, edit text and a list view.
I want to change that implementation and to show the list view on a new popup window only when the user press the select all button.
I've added my code, thanks.
public class Notepadv1 extends ListActivity implements OnClickListener {
private WordsDbAdapter mDbHelper;
private Button selectAllButton;
private PopupWindow mPopup;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
selectAllButton = (Button)findViewById(R.id.selectAll);
selectAllButton.setOnClickListener(this);
mDbHelper = new WordsDbAdapter(this);
mDbHelper.open();
fillData();
}
public void onClick(View v) {
switch(v.getId()){
case(R.id.selectAll):
selectAll();
break;
}
}
private void selectAll(){
}
private void fillData() {
Cursor c = mDbHelper.fetchAllNotes();
startManagingCursor(c);
String[] from = new String[] { WordsDbAdapter.KEY_WORD };
int[] to = new int[] { R.id.text1 };
SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.words_row, c, from, to);
setListAdapter(notes);
}
}

Show a simple Alert Dialog with a list:
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();

Yes you can do it.
1st way:
define an activity as Dialog with the below attribute in AndroidManifest.xml file:
<activity android:theme="#android:style/Theme.Dialog" />
2nd way:
You can inflate the XML layout inside the dialog as below:
Dialog dialog = new Dialog(context);
LayoutInflater li = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.my_layout, null, false);
dialog.setContentView(v);
dialog.show();
for example:
edit: link fixed
Android Dialog with ListView.

If using a custom ArrayAdapter, use setAdapter():
AlertDialog.Builder builder = new Builder(this)
.setTitle("Dialog Title")
.setAdapter(new CustomAdapter(context, items, ...), (dialog, itemPosition) -> {
// Handle item click
});
builder.show();

Related

Displaying ListView in alertDailog android

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();
}

Updating list fragment with list adapter

Currently ran into an issue trying to update a list fragment with a dialogfragment input (or dummy input) everything compiles but don't see any change to the list.
Please let me know what you think. Thanks.
public class NewEventDialogFragment extends DialogFragment {
private List<GlobalClass> mItems;
EditText editText;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//editText = (EditText) findViewById(R.id.editText);
builder.setMessage("What Would You Like to Name the Event?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mItems = new ArrayList<GlobalClass>();
mItems.add(new GlobalClass("Whoiszzzzzzzzzzzzzzthis", "Adsdfdsdomg"));
mItems.add(new GlobalClass("Whodsfzzzzzzzzzzzzzsdfsisthis", "Addsdfdfomg"));
mItems.add(new GlobalClass("Whoisthzzzzzzzzzzzzzzsdfdsfis", "Addosdfsdfmg"));
// Create the adapter to convert the array to views
MainTabsPagerAdapter adapter = new MainTabsPagerAdapter(getActivity(), mItems);
// Attach the adapter to a ListView
adapter.addAll(mItems);
adapter.notifyDataSetChanged();
//setListAdapter(new MainTabsPagerAdapter(getActivity(), mItems));
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
View view = getActivity().getLayoutInflater().inflate(R.layout.neweventdialog_fragment, null);
builder.setView(view);
return builder.create();
}
}
private List<GlobalClass> mItems; // ListView items list
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initialize the items list
mItems = new ArrayList<GlobalClass>();
Resources resources = getResources();
mItems.add(new GlobalClass("Whoisthis", "Adsdfdsdomg"));
mItems.add(new GlobalClass("Whodsfsdfsisthis", "Addsdfdfomg"));
mItems.add(new GlobalClass("Whoisthsdfdsfis", "Addosdfsdfmg"));
// initialize and set the list adapter
setListAdapter(new MainTabsPagerAdapter(getActivity(), mItems));
}
You need to have ListView in your layout R.layout.neweventdialog_fragment and bind this widget to your view in code, then setAdapter on it.
View view = getActivity().getLayoutInflater().inflate(R.layout.neweventdialog_fragment, null);
ListView listView = (ListView) view.findViewById(R.id.listView); // you bind to listView your widget
listView.setAdapter(adapter); // you set adapter
builder.setView(view);
return builder.create();
When you wants to appear DialogFragment, you use NewEventDialogFragment.newInstance().show(getSupportFragmentManager(),CURRENT_FRAGMENT_TAG);

Android FragmentDialog's state and device rotation

AlertDialog with DialogFragment will restore any data (edited text in text view's, chosen element in single choice) after device rotation. And will not restore checked items in multichoice mode. To be accurate - it will remember fields initiated with false and always reset fields initiated with true (reset back to true after rotate).
That is very strange, what am i doing wrong? I want it to restore all data (especially when all the views managed by dialog itself).
UPD 1: I actually understand, that i can track any user interaction with UI in dialog and save it between dialog/fragment instances in bundles or even static variables. BUT it already manage to save my custom layout's state (edittext+checkbox) and singlechoice selection by itself. And only multichoice behaves wrong with similar code. That is what i want to understand.
Working demo below.
Tested on Nexus 5 / Android 4.4.2
Activity with only one method implemented
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button single = (Button) findViewById(R.id.single);
single.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
df_single newDialog = new df_single();
newDialog.show(MyActivity.this.getFragmentManager(), "dialog");
}
});
Button multi = (Button) findViewById(R.id.multi);
multi.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
df_multi newDialog = new df_multi();
newDialog.show(MyActivity.this.getFragmentManager(), "dialog");
}
});
}
It's layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:id="#+id/single" android:layout_width="200dp" android:layout_height="wrap_content" android:text="list single"/>
<Button android:id="#+id/multi" android:layout_width="200dp" android:layout_height="wrap_content" android:text="list multi"/>
DialogFragment for single choice
public class df_single extends DialogFragment {
public df_single() { }
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Single");
String[] items = new String[]{"1", "2", "3", "4", "5"};
builder.setSingleChoiceItems(items, 1, null);
return builder.create();
}
}
DialogFragment for multi choice
public class df_multi extends DialogFragment {
public df_multi() { }
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Multi");
String[] items = new String[]{"1", "2", "3", "4", "5"};
boolean[] checked = new boolean[]{true, false, true, false, true};
builder.setMultiChoiceItems(items, checked, null);
Dialog answer = builder.create();
return answer;
}
}
You can persist the selected element using onSaveInstanceState method and restore the selected element position.
public class df_single extends DialogFragment {
public df_single() { }
public static final int DEFAULT_ELEMENT_POSITION;
int selectedElement;
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Single");
selectedElement = savedInstanceState.getInt("selectedElement", DEFAULT_ELEMENT_POSITION);
String[] items = new String[]{"1", "2", "3", "4", "5"};
builder.setSingleChoiceItems(items, selectedElement, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selectedElement = which;
}
});
return builder.create();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("selectedElement", selectedElement);
super.onSaveInstanceState(savedInstanceState);
}
}
Ok. I can achieve desired behavior (init once and recreate universally on each rotation, get result in positive button clickListener and do not preserve state by myself) with the following code modifications
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Multi");
final String[] items = new String[]{"1", "2", "3", "4", "5"};
boolean[] checked = new boolean[]{true, false, true, false, true};
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View listRoot = inflater.inflate(R.layout.list, null);
builder.setView(listRoot);
final ListView list = (ListView)listRoot.findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.select_dialog_multichoice, android.R.id.text1, items);
list.setAdapter(adapter);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
for (int i = 0; i < checked.length; i++)
list.setItemChecked(i, checked[i]);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int which) {
View view = ((AlertDialog) dialogInterface).findViewById(R.id.list);
assert view != null;
assert view instanceof ListView;
SparseBooleanArray checked = ((ListView) view).getCheckedItemPositions();
for (int i = 0; i < items.length; i++)
Log.d("checked", checked.get(i)?"YES":"NO");
}
});
return builder.create();
}
Where list.xml is just
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:id="#+id/list" android:layout_width="match_parent" android:layout_height="match_parent"/>
</LinearLayout>
That is semi-answer, cause i still don't know what is the difference for android bewtween setSingleChoiceItems and setMultiChoiceItems in context of state auto save.

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.

DragSortListView and AlertDialog?

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

Categories

Resources