Add dropdownlist spinner to alert dialogue Android Studio - android

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.

Related

I want spinner to automatically be opened when the page gets loaded android

I want the spinner drop down to get opened automatically when the page gets loaded.
what can i do for that?
<Spinner
android:entries="#array/cities_arrays"
android:id="#+id/spinner"
android:layout_width="230sp"
android:gravity="center_horizontal"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:spinnerMode="dropdown"
tools:layout_editor_absoluteY="16dp"
android:background="#drawable/spinner_styling"
android:layout_marginLeft="80sp"
android:layout_marginRight="80sp"
android:layout_marginTop="10sp"
android:layout_below="#+id/app_bar"/>
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
placesList = new ArrayList<>();
cities = getResources().getStringArray(R.array.cities_arrays);
Spinner spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, cities);
listView = (ListView) findViewById(R.id.listView);
// This is to avoid automatic keypad opening as soon as the page loads.
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
placesList.clear();
autoCompView = (AutoCompleteTextView) findViewById(R.id.autoCompleteText);
autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this, R.layout.list_item));
autoCompView.setOnItemClickListener(this);
listAdapter = new ListViewAdapter(this, R.layout.row,placesList);
spinner.setAdapter(adapter);
// Open the Spinner when your activity will load...
spinner.performClick();
mButton = (Button) findViewById(R.id.plus_button);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// inflate alert dialog xml
LayoutInflater li = LayoutInflater.from(mContext);
View dialogView = li.inflate(R.layout.custom_dialog, null);
android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(mContext);
// set title
alertDialogBuilder.setTitle("Add Location");
// set custom dialog icon
//alertDialogBuilder.setIcon(R.drawable.ic_launcher);
// set custom_dialog.xml to alertdialog builder
alertDialogBuilder.setView(dialogView);
final EditText userInput = (EditText) dialogView
.findViewById(R.id.autoCompleteTextView);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
//etOutput.setText(userInput.getText());
dialog.cancel();
}
})
.setNegativeButton("Done",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
// create alert dialog
android.support.v7.app.AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
index = arg0.getSelectedItemPosition();
city = cities[index];
if(index != 0) {
PLACES_OF_INTEREST_URL = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" + city + "+point+of+interest&language=en&key=" + API_KEY + "";
listView.clearAnimation();
listAdapter.clear();
new GetPlaces().execute();
listAdapter.addAll(placesList);
listView = (ListView) findViewById(R.id.listView);
listView.invalidateViews();
listAdapter.notifyDataSetChanged();
listView.setAdapter(listAdapter);
System.out.println(city);
Toast.makeText(getApplicationContext(), "Selected: " + city, Toast.LENGTH_LONG).show();
}
index = -1;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
Toast.makeText(getApplicationContext(),"Please Select a City!", Toast.LENGTH_LONG).show();
}
});
}
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.application.microsoft.wayfarer, PID: 24758
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.application.microsoft.wayfarer/com.application.microsoft.wayfarer.activities.MainActivity}: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
You can achieve this like below :-
Spinner yourSpinner = (Spinner) findViewById(R.id.yourSpinner);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this,R.array.planets, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
yourSpinner.setAdapter(adapter);
// Open the Spinner when your activity will load...
yourSpinner.performClick();
and in your method comment this below line
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

Populating Spinner using a HashMap?

I am trying to populate a spinner using items from a custom class I created via a simple adapter, containing a HashMap. My app keeps crashing when I use setSimpleAdapter(), so I commented it out. But when I use spinner1.setAdapter(dataAdapter), it shows no items on the spinner. Here's my code:
This is in my onCreate():
spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter <CharSequence> dataAdapter =
new ArrayAdapter <CharSequence> (this, android.R.layout.simple_spinner_item );
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
//setSimpleAdapter();
// Spinner item selection Listener
addListenerOnSpinnerItemSelection();
// Button click Listener
addListenerOnButton();
// Add spinner data
public void addListenerOnSpinnerItemSelection(){
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
//get the selected dropdown list value
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("X");
alertDialog.setMessage("" + String.valueOf(spinner1.getSelectedItem()));
alertDialog.setButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//Dismisses alert
alertDialog.dismiss();
}
});
alertDialog.show();
}
});
}
Can anyone point me in the right direction? I have been googling for like an hour now. Any help will be appreciated.
Well you didn't post half enough code, but say you have a HashMap<String, Object> then you'd wanna do something like this, passing the array of values into the constructor:
Collection<Object> vals = hashMap.values();
Object[] array = vals.toArray(new Object[vals.size()]);
ArrayAdapter<CharSequence> dataAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, array);
Just replace Object with whatever your custom class is and ensure that you override toString() to define what should be displayed as text.

AutoCompleteTextView in a AlertDialog Builder

I have tried to work this out but nothing pops into my head, the following code is a part of an application that has movies and if i click a search button it creates a dialog builder with a AutoCompleteTextView for typing a name of a movie.
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(ThisScreen.search_context, android.R.style.Theme_Black));
///// autocomplete thingie
String[] name_mov = new String[movie_categ.size()];
name_mov = movie_categ.toArray(name_mov);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, name_mov);
LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View search_View = inflater.inflate(R.layout.this_movie_search, null);
myAutoComplete = (AutoCompleteTextView)
search_View.findViewById(R.id.movie_name);
myAutoComplete.setAdapter(adapter);
myAutoComplete.setThreshold(2);
/////
alertDialogBuilder.setView(searchView);
alertDialogBuilder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
isFirstDialog = 0;
}
});
alertDialog = alertDialogBuilder.create();
if (movie_categ.isEmpty() )
{
Toast.makeText(ThisScreen.search_context, "Verify net conn.", Toast.LENGTH_LONG).show();
isFirstDialog = 0;
}
else alertDialog.show();
and this_movie_search.xml has
<AutoCompleteTextView
android:id="#+id/movie_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#+id/button_search"
android:textColorHint="#android:color/white"
android:hint="#string/search_hint"
android:ems="10"
android:maxLength="50"
/>
The list with the suggestions doesnt appear, any ideas why?
I searched for the answer for too long and didn't saw the obvious, i should have declared my myAutoComplete from the beginning as 'AutoCompleteTextView' type, and it works.
final AutoCompleteTextView myAutoComplete = (AutoCompleteTextView) searchView.findViewById(R.id.AutoCompleteTextView_declared_in_the_xml);
// autocomplete thingie
String[] name_mov = new String[movie_categ.size()];
name_mov = movie_categ.toArray(name_mov);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, name_mov);
myAutoComplete.setAdapter(adapter);
myAutoComplete.setThreshold(2);
//

Android - Spinner not able to select items

I have a problem with my spinner. I add the items on the spinner dinamically, from a edittext when a button it's pressed. The items are correctly shown when the spinner is pressed, but no selection can be done and there's no display on the spinner.
Here's the code:
final ArrayList<String> players = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_dropdown_item, players);
final Spinner spinnerplayers = (Spinner)findViewById(R.id.spinnerplayers);
final ImageButton addbutton = (ImageButton)findViewById(R.id.addbutton);
final EditText editname = (EditText)findViewById(R.id.editname);
final EditText editnum = (EditText)findViewById(R.id.editnum);
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
players.add(editname.getText().toString()+ " " + editnum.getText().toString());
editname.setText("");
editnum.setText("");
}
});
spinnerplayers.setAdapter(adapter);
final ImageButton removebutton = (ImageButton)findViewById(R.id.removebutton);
removebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//players.remove(spinnerplayers.getSelectedItem().toString());
}
});
If it's needed, the spinner xml is:
<Spinner
android:id="#+id/spinnerplayers"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1" />
Any idea about where's the problem?
Thanks in advance.
Have you tried to specify:
adapter.setNotifyOnChange(true);
to refresh adapter showing each add/remove you make ?
The reason is you set it with android.R.layout.simple_spinner_item.
You can write your own Adapter class:
Spinner spinner = (Spinner) findViewById(R.id.mySpinner);
spinner.setAdapter(new MyCustomAdapter(CLASS.this, R.layout.spinner_layout, players));
Then it will look like the way you design in spinner_layout
You have to make a custom adapter for this if you mean the clicklistenrs on your button are not working. You will apply listeners in getView method of the adapter.
Add you have to add OnItemSelectedListener.
YOUR_SPINNER.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
The position gives you your item.

Create ListView programmatically

Hi I am new in Android. Could anyone tell me pls whats the wrong with the following code:
public class ListApp extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView lText = new TextView(this);
lText.setId(0);
ListView lView = new ListView(this);
String[] lStr = new String[]{"AA","BB", "CC"};
ArrayAdapter lAdap = new ArrayAdapter(this,lText.getId(),lStr);
lView.setAdapter(lAdap);
lView.setFocusableInTouchMode(true);
setContentView(lView);
}
}
here's a solution that does not require you to write any xml layouts. it uses standard android layouts where possible and no inflation is necessary:
Dialog dialog = new Dialog(this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Color Mode");
ListView modeList = new ListView(this);
String[] stringArray = new String[] { "Bright Mode", "Normal Mode" };
ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, stringArray);
modeList.setAdapter(modeAdapter);
builder.setView(modeList);
dialog = builder.create();
Try this..
Paste the following code in list_item.xml.
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" android:textColor="#ffffff" android:textStyle="bold" android:background="#drawable/border_cell">
</TextView>
Here is the activity class....
public class UsersListActivity extends ListActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] statesList = {"listItem 1", "listItem 2", "listItem 3"};
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item,
statesList));
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"You selected : "+((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
Best practice is to separate view (xml layout) and controller (Activity).
If you dont want this, try to put
setContentView(lView);
at the beginning of onCreate
public class ListApp extends ListActivity
Make a layout XML file with your listview and use findViewById to set it's adapter after first setting the content view to your layout

Categories

Resources