number picker can't set up - android

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

Related

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"

Unable to add items to ListView

I have a dialog where I need to add name and If I click Ok button that name entered in the edittext should be added to my ListView which is in fragment
This is my homefragment:
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
Here is my input-dialog:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="#dimen/activity_vertical_margin"
android:orientation="vertical" >
<TextView
android:id="#+id/list_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter name for shopping list" />
<EditText
android:id="#+id/list_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
This is my fragment_home:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView android:id="#+id/itemslistView"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_marginTop="75dp"/>
</RelativeLayout>
Here is my dialog code:
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
View promptView = layoutInflater.inflate(R.layout.input_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView
.findViewById(R.id.list_text);
// setup a dialog window
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
LayoutInflater layoutInflater = LayoutInflater
.from(MainActivity.this);
View lstview = layoutInflater.inflate(
R.layout.fragment_home, null);
lv = (ListView) lstview
.findViewById(R.id.itemslistView);
List<String> MyList = new ArrayList<String>();
String NewListname=editText.getText().toString();
MyList.add(NewListname);
Toast.makeText(MainActivity.this, NewListname, Toast.LENGTH_LONG).show();
ArrayAdapter<String> adp = new ArrayAdapter<String>(
MainActivity.this, R.layout.list, MyList);
lv.setAdapter(adp);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
This is my HomeFragment:
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Fragment;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
public class HomeFragment extends Fragment {
public HomeFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container,
false);
return rootView;
}
}
My problem is I'm able to get the text from edittext as shown with toast but unable to add it to listview.
Can anyone say me where am I going wrong?
After adding text in your MyList you just called adapter.notifyDataSetChanged();
No need to setAdapter(adp); again
Please try with follwing code (i never tried in devices)
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
View promptView = layoutInflater.inflate(R.layout.input_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView
.findViewById(R.id.list_text);
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
View lstview = layoutInflater.inflate(R.layout.fragment_home, null);
lv = (ListView) lstview.findViewById(R.id.itemslistView);
List<String> MyList = new ArrayList<String>();
final ArrayAdapter<String> adp = new ArrayAdapter<String>(MainActivity.this,
R.layout.list, MyList);
lv.setAdapter(adp);
// setup a dialog window
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String NewListname = editText.getText().toString();
MyList.add(NewListname);
Toast.makeText(MainActivity.this, NewListname,
Toast.LENGTH_LONG).show();
adp.notifyDataSetChanged();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
Try This:
In your HomeFragment:
List<String> MyList = new ArrayList<String>();
ListView lv=(ListView)findViewById(R.id.itemslistView);
protected void showInputDialog()
{
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
View promptView = layoutInflater.inflate(R.layout.input_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView
.findViewById(R.id.list_text);
// setup a dialog window
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String NewListname=editText.getText().toString();
MyList.add(NewListname);
Toast.makeText(MainActivity.this, NewListname, Toast.LENGTH_LONG).show();
ArrayAdapter<String> adp = new ArrayAdapter<String>(
MainActivity.this, R.layout.list, MyList);
lv.setAdapter(adp);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}

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.

Can't change a Custom DialogFragment layout dynamically

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.

Multiple choice AlertDialog with custom Adapter

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.

Categories

Resources