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.
Related
I have successfully created a working AlertDialog for my Android application:
public class MyClass extends DialogFragment{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
ArrayList selectedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.pick_toppings)
builder.setMultiChoiceItems(R.array.my_array, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
selectedItems.add(which);
} else if (selectedItems.contains(which)) {
selectedItems.remove(Integer.valueOf(which));
}
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// do stuff here ...
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// do stuff here ...
}
});
return builder.create();
}
}
This MultiChoiceItems list is backed by an array in /res/values/array.xml
<resources>
<array name="my_array">
<item>item 01</item>
<item>item 02</item>
<item>item 03</item>
<item>item 04</item>
<item>item 05</item>
</array>
</resources>
From my Activity, I call the AlertDialog this way:
MyClass myClass = new MyClass();
myClass.show(getSupportFragmentManager(), "My Dialog");
What I want to do now is use a custom layout with the AlertDialog so that I can do things like alternate-row shading, custom buttons, and add an EditText so I can have an "other" option with the ability to fill in the "other".
After doing some googling, it looks like I need to create a new layout, and set the view of the AlertDialog to this layout. So, I created a layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="other"
android:textSize="18sp"/>
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
Then I added this to my DialogFragment class:
LayoutInflater layoutInflater = getActivity().getLayoutInflater();
View view = layoutInflater.inflate(R.layout.my_new_layout, null);
then
builder.setView(view);
As you can guess, this did not work. The new CheckBox and EditText was inserted after my other checkboxes that were populated from my array, but it looks terrible, and I don't appear to have any control over the appearance of the checkboxes created from the array.
Like I said, I would like the ability to add this new CheckBox/EditText combination, as well as have the ability to customize the look of the entire AlertDialog.
I really want to use the array from /res/values/array.xml so that I do not have to hard code a new option if I want to add new items to the list.
Is what I am wanting to do possible? If so, some advice would be great.
Thanks
This is what I would like my AlertDialog to look/act like:
Ok, I finally figured this out on my own. Here is my resolution:
New Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="right">
</LinearLayout>
New Class:
public class MyClass extends DialogFragment{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String[] theOptions = getResources().getStringArray(R.array.options);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.pick_toppings)
LayoutInflater layoutInflater = getActivity().getLayoutInflater();
LinearLayout view = (LinearLayout) layoutInflater.inflate(R.layout.my_layout, null);
for(String option : theOptions){
CheckBox checkbox = new CheckBox(getContext());
checkbox.setText(option);
view.addView(checkbox);
}
LinearLayout otherLinearLayout = new LinearLayout(getContext());
otherLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
otherLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
otherLinearLayout.setId(R.id.otherLinearLayout);
CheckBox otherCheckBox = new CheckBox(getContext());
otherCheckBox.setText("other");
otherCheckBox.setId(R.id.otherCheckBox);
EditText otherEditText = new EditText(getContext());
otherEditText.setId(R.id.otherEditText);
otherLinearLayout.addView(otherCheckBox);
otherLinearLayout.addView(otherEditText);
view.addView(otherLinearLayout);
builder.setView(view);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// do stuff here ...
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// do stuff here ...
}
});
return builder.create();
}
}
You can do something like this, get the array using
String[] myarray = getResources().getStringArray(R.array.testArray);
and the create new checkbox objects using each array item and set it to the inflated view
LinearLayout layout2 = new LinearLayout(context); layout2.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
and loop through your array list
layout2.addView(new Checkbox(context));
and finally add the parent linear layout to the inflated view inflatedView.addView(layout2);
Create Custom Dialog Fragment and add all items and checkboxes inside
the new layout defined by programmatically i.e dynamically.Write the
code for checkItemSelectedListener in your code.
I'm trying to add a search form with a edittext and dropdownlist spinner to alert dialogue. I have managed to get the edit text to display, but I cannot figure out how to add the spinner. I'm new to android so any help would be appreciated.
private void LoadSearchDialogue()
{
android.app.AlertDialog.Builder alertDialogSearchForm = new android.app.AlertDialog.Builder(this);
alertDialogSearchForm.setTitle("Search Form");
alertDialogSearchForm.setMessage("Please complete form");
final EditText textViewInputUsername = new EditText(this);
final Spinner spinnerSearchOptions = new Spinner(this);
Spinner dropdownSearchOptions = (Spinner)findViewById(R.id.spinnerSearchOptions);
String[] items = new String[]{"Customer", "Employee","Date" };
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
dropdownSearchOptions.setAdapter(adapter);
mQuery = (EditText) findViewById(R.id.query);
mSearchOption = (Spinner) findViewById(R.id.spinnerSearchOptions);
alertDialogSearchForm.setView(textViewInputUsername);
alertDialogSearchForm.setPositiveButton("Continue",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Do nothing here, overriding alert dialogue button
}
});
final android.app.AlertDialog dialog = alertDialogSearchForm.create();
dialog.show();
dialog.getButton(android.app.AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Boolean closeAlertDialogueOnValidInput = false;
//Check if query is entered,
String mQueryString = textViewInputUsername.getText().toString().trim();
if(mQueryString.length()<=0)
{
Toast.makeText(SearchActivity.this, "Please enter query", Toast.LENGTH_SHORT).show();
}
else
{
String q = mQueryString.toString();
String o = mSearchOption.getSelectedItem().toString();
SearchResults(q, o);
}
if(closeAlertDialogueOnValidInput)
dialog.dismiss();
}
});
}
Use the below code
public class WvActivity extends Activity {
TextView tx;
String[] s = { "India ", "Arica", "India ", "Arica", "India ", "Arica",
"India ", "Arica", "India ", "Arica" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ArrayAdapter<String> adp = new ArrayAdapter<String>(WvActivity.this,
android.R.layout.simple_spinner_item, s);
tx= (TextView)findViewById(R.id.txt1);
final Spinner sp = new Spinner(WvActivity.this);
sp.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
sp.setAdapter(adp);
AlertDialog.Builder builder = new AlertDialog.Builder(WvActivity.this);
builder.setView(sp);
builder.create().show();
}
}
I suggest that you create a simple xml layout for your dialog:
<!-- alert.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">
<EditText
android:id="#+id/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Spinner
android:id="#+id/mySpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
After that you inflate a View from this layout file, set this view in setView method, fill the Spinner with data and do all the stuff that you need to do. All the things that you currently do to define behavior for button clicks will remain the same; but the listeners for your EditText and Spinner, if needed, will be set outside the Dialog (with findViewById and setOnClickListener).
To inflate a View from xml you need to get LayoutInflater and use it to create a View:
View alertView = getLayoutInflater().inflate(R.layout.alert, null);
To populate the Spinner with data, you should use an Adapter. There is some code from here:
// you need to have a list of data that you want the spinner to display
List<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("item1");
spinnerArray.add("item2");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner sItems = (Spinner) findViewById(R.id.spinner1);
sItems.setAdapter(adapter);
If you would like to stick to your way of creation of the View, you need to add not only your EditText to your AlertDialog, but a ViewGroup (LinearLayout for example), that will contain both EditText and Spinner.
I have problem with a number picker in Android. It displays only 0 value between two horizontal lines. It looks like my settings which I'm trying to set in the code aren't working.
My xml layout code:
<?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" >
<NumberPicker
android:id="#+id/np"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="64dp"/>
</LinearLayout>
My DialogFragment code:
public class MyDialogFragment extends DialogFragment{
public static MyDialogFragment newInstance(int title) {
MyDialogFragment frag = new MyDialogFragment();
Bundle args = new Bundle();
args.putInt("title", title);
frag.setArguments(args);
return frag;
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = getArguments().getInt("title");
// Create the array of numbers that will populate the numberpicker
final String[] nums = new String[21];
for(int i=0; i<nums.length; i++) {
nums[i] = Integer.toString(i*5);
}
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.scaledialog, null);
//set up number picker
NumberPicker np = (NumberPicker) view.findViewById(R.id.np);
np.setMaxValue(20);
np.setMinValue(5);
np.setWrapSelectorWheel(true);
np.setDisplayedValues(nums);
np.setValue(5);
return new AlertDialog.Builder(getActivity())
.setView(inflater.inflate(R.layout.scaledialog, null))
//.setIcon(R.drawable.alert_dialog_icon)
.setTitle(title)
.setPositiveButton(R.string.alert_dialog_ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// ((FragmentAlertDialog)getActivity()).doPositiveClick();
}
}
)
.setNegativeButton(R.string.alert_dialog_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//((FragmentAlertDialog)getActivity()).doNegativeClick();
}
}
)
.create();
}
TRY THIS !!
setup should be queue after the dialog was build
so use Post() and Runnable() to achieve this.
final NumberPicker np = (NumberPicker) view.findViewById(R.id.np);
np.post(new Runnable() {
#Override
public void run() {
String[] nums = new String[21];
for(int i=0; i<nums.length; i++) {
nums[i] = Integer.toString(i*5);
}
np.setMaxValue(20);
np.setMinValue(5);
np.setWrapSelectorWheel(true);
np.setDisplayedValues(nums);
np.setValue(5);
}
});
So reading through the Google API Guides I came across how to load a custom layout within an Alert Dialog Box here.
I wrote a class that extends a DialogFragment class like this:
String product;
String description;
String company;
public void getAdInfo(String p, String d, String c)
{
product = p;
description = d;
company = c;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.ad_dialog, null));
TextView pt = (TextView) getView().findViewById(R.id.product);
pt.setText(product);
TextView dt = (TextView) getView().findViewById(R.id.description);
dt.setText(description);
TextView ct = (TextView)getView().findViewById(R.id.company);
ct.setText(company);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do something
}
});
builder.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dismiss();
}
});
return builder.create();
}
}
Here's the layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/product"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textIsSelectable="false"
/>
<TextView
android:id="#+id/company"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textIsSelectable="false"
/>
<TextView
android:id="#+id/description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textIsSelectable="false"
/>
I instanciate the Dialog within an OnClickListener with these lines.
AdDialogFragment ad = new AdDialogFragment();
ad.getAdInfo(j.getAttribute("product"), j.getAttribute("description"), j.getAttribute("company"));
ad.show(getFragmentManager(), null);
j being an element from an xml node.
When I click on the button that's supposed to run the dialog I get this NullPointerException error from LogCat:
E/AndroidRuntime(10483): at com.onix.mallard.android.guifrag.AdDialogFragment.onCreateDialog(AdDialogFragment.java:29)
The error refers to the line:
pt.setText(product);
Ultimately, it crashes the app completely. How can I change the layout of a DialogFragment dynamically? The Android API Guide says that DialogFragments are bound by the same lifecycle as Fragments, but that doesn't tell me much since they don't make use of FragmentTransactions (to my knowledge). If this is not possible and I need to instance the information as an Activity, no harm is done.
If it helps, the dialog is called from within a Fragment.
Here's how I would do that (untested code) ;)
Your custom Dialog:
public class AdDialogFragment extends DialogFragment {
String mProduct;
String mDescription;
String mCompany;
TextView mProductTV;
TextView mDescriptionTV;
TextView mCompanyTV;
public void setAdInfo(String product, String desc, String company)
{
mProduct = product;
mDescription = desc;
mCompany = company;
}
public AdDialogFragment() {
super();
}
public static AdDialogFragment newInstance() {
return new AdDialogFragment();
}
public Dialog onCreateDialog(final Bundle savedInstanceState) {
LayoutInflater factory = LayoutInflater.from(getActivity());
final View content = factory.inflate(R.layout.ad_dialog, null);
mProductTV = (TextView) content.findViewById(R.id.product);
mDescriptionTV = (TextView) content.findViewById(R.id.description);
mCompanyTV = (TextView) content.findViewById(R.id.company);
fillTextViews();
AlertDialog.Builder dialog;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
dialog = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), R.style.Theme.DeviceDefault.Dialog.)); //can't remember the name or create a custom theme.
} else {
dialog = new AlertDialog.Builder(getActivity());//anything below honeycomb can die :).
}
// now customize your dialog
dialog.setTitle(getActivity().getString(R.string.some_title_if_any))
.setView(content)
.setCancelable(true) //this is the default I think.
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do something
}
});
.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dismiss();
}
});
return dialog.create();
}
private void fillTextViews() {
mProductTV.setText(mProduct);
mDescriptionTV.setText(mDescription);
mCompanyTV.setText(mCompany);
}
And this is how you call it from an Activity for example:
public void showYourFancyDialog() {
AdDialogFragment dialog = AdDialogFragment.newInstance();
dialog.setAdInfo(yourProduct, yourDescription, yourCompany);
dialog.show(getSupportFragmentManager(), "dialog");
}
Using patterns from Google's documentation
You could try the following, it has worked for me:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.ad_dialog, null));
builder.setView(v);
And then call findViewById like such:
v.findViewById();
I solved this issue a while ago by instead of recurring to the AlertDialog class I used a regular Activity. In AndroidManifest.xml, the activity specification has the following line.
android:theme="#styles/Theme.HoloLight.Dialog"
A word of advice, Linear Layout doesn't work. Try RelativeLayout.
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();