android | create a dialog spinner from menu button pressed - android

I want to create a language selector for my app. I created a button in the menu layout and I want a spinner to open when one of option menu is clicked . I'm a beginner so I'd love if you could explain your answers.

first you have to create an xml layout where your spinner element will be placed
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- Spinner Element -->
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="Select Language"
/>
</LinearLayout>
then i your activity where you would like to show the snipper you should implement OnItemSelectedListener interface for handling the selections of the spinner
public class SnipperActivity extends Activity implements OnItemSelectedListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//here you get the reference to the spinner element declared in your xml layout
Spinner spinner = (Spinner) findViewById(R.id.spinner);
//set the listener to the spinner
spinner.setOnItemSelectedListener(this);
//here you create an arraylist for the items to be displayed in your spinner element
List<String> languages = new ArrayList<String>();
languages.add("English");
languages.add("Greek");
}
//define an adapter for the spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, languages);
//set the style of the snipper, in this case a listview with a radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_it em);
//attach the adapter to your spinner element
spinner.setAdapter(dataAdapter);
}
to handle spinner elements selection you have to ovveride the following method inside SnipperActivity class
#Override
public void onItemSelected(AdapterView parent, View view, int position, long id) {
// On selecting a spinner item
String language = parent.getItemAtPosition(position).toString();
//show a spinner item
Log.e("TAG", "Spinner item selected " + language);
}

Have a look at this article on creating custom dialogs:
http://android-developers.blogspot.co.uk/2012/05/using-dialogfragments.html
IMHO spinners are not very flexible. I'd use a listview in my dialog if I were you, but that choice is yours :)

Related

My spinner does not display the selected item and doesn't call onItemSelected

I have an android spinner that allows the user to select a translation. I can tap the spinner and it will reveal a list with available translations, but when I select an item in the list it will not appear in the spinner and neither does the onItemSelected method get called.
Here is the xml code for the spinner:
<Spinner
android:id="#+id/trans_list"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/chap_list"
android:layout_weight="1" />
Here is the relevant code for initiating the spinner. (edit) This code is ran from inside a Fragment class and not from my MainActivity class:
trans_spinner = v.findViewById(R.id.trans_list);
ArrayAdapter<String> adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_spinner_dropdown_item, translations);
trans_spinner.setAdapter(adapter);
trans_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String translation = trans_spinner.getItemAtPosition(trans_spinner.getSelectedItemPosition()).toString();
Log.d("trans", translation);
Toast.makeText(view.getContext(), translation, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Log.d("test", "1");
}
});
trans_spinner.setSelection(1);
Neither the onItemSelected() or onNothingSelected() method gets called when I select an item. I found this page describing an issue very similar to mine:
Android Spinner will not launch OnItemSelected and current selected item is not displayed in Spinner
However the user did not present a clear solution to their problem so it doesn't help me much.
I am not sure if it is relevant, but the items in the spinner are taken from an online webpage that provides JSON data to fill the spinner. This seems to work, as the options do appear in the spinner list. The issue is that upon selecting one of them, the spinner appears empty and the listener doesn't do anything.
So I found out that the issue was actually because of how I obtained the list of strings to put inside the spinner. As mentioned in the original post, I am loading the string values from a webpage in JSON format. I'm using the Retrofit2 API for this.
The problem was caused by the fact that I was downloading this data and then initializing the spinner both in the onCreateView() method of my fragment. What I did to fix it is I created a new method that initializes the spinner, and then I would call it from the onResponse() method used by the Retrofit API. This means that it doesn't initialize the spinner until after it has finished downloading/populating the list of strings.
<Spinner
android:id="#+id/planets_spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
f the available choices for your spinner are pre-determined, you can provide them with a string array defined in a string resource file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
</resources>
With an array such as this one, you can use the following code in your Activity or Fragment to supply the spinner with the array using an instance of ArrayAdapter:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
When the user selects an item from the drop-down, the Spinner object receives an on-item-selected event.
To define the selection event handler for a spinner, implement the AdapterView.OnItemSelectedListener interface and the corresponding onItemSelected() callback method. For example, here's an implementation of the interface in an Activity:
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
...
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
The AdapterView.OnItemSelectedListener requires the onItemSelected() and onNothingSelected() callback methods.
Then you need to specify the interface implementation by calling setOnItemSelectedListener():
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
If you implement the AdapterView.OnItemSelectedListener interface with your Activity or Fragment (such as in the example above), you can pass this as the interface instance.
Java Code
public class MainActivity extends AppCompatActivity {
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = findViewById(R.id.spinner);
List<String> translations = new ArrayList<>();
translations.add("string1");
translations.add("string2");
translations.add("string3");
translations.add("string4");
translations.add("string5");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, translations);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Object getPosition = parent.getItemAtPosition(position);
String value = getPosition.toString();
Toast.makeText(getActivity(), value, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
XML Code
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner">
</Spinner>
Add this code after init adapter
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
And to get the selected item inside onItemSelected
translations.get(position)

Text Color Changes to White when select item from searchable spinner

I am using custom searchable spinner in my android application. In one of my activity, I am using two searchable spinners. one for Citys and one for area locations. On selection of 1st Spinner item, I am Changing the adapter of the 2nd spinner to show Area location of that respective City's. but when I select an item of the 2nd spinner, Text Color of the selected item of spinner changes to White. How to stop it.
I have Attached ScreenShots and Code below.
Before Selecting Any Item
After Selecting Items Of Both Spinner
Activity.java
citySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// Create an ArrayAdapter using the string array and a default spinner layout
if(citySpinner.getItemAtPosition(i).equals("Mumbai"))
{
adapterArea = ArrayAdapter.createFromResource(getApplicationContext(),
R.array.mumbai, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapterArea.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
areaSpinner.setAdapter(adapterArea);
}
else if(citySpinner.getItemAtPosition(i).equals("Delhi"))
{
adapterArea = ArrayAdapter.createFromResource(getApplicationContext(),
R.array.delhi, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapterArea.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
areaSpinner.setAdapter(adapterArea);
}
else if(citySpinner.getItemAtPosition(i).equals("Thane"))
{
adapterArea = ArrayAdapter.createFromResource(getApplicationContext(),
R.array.thane, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapterArea.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
areaSpinner.setAdapter(adapterArea);
}
else if(citySpinner.getItemAtPosition(i).equals("Select City"))
{
buttonAdd.setEnabled(false);
buttonAdd.setVisibility(View.GONE);
adapterArea = ArrayAdapter.createFromResource(getApplicationContext(),
R.array.blank, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapterArea.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
areaSpinner.setAdapter(adapterArea);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
areaSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(areaSpinner.getItemAtPosition(i).equals("Select Area")|| areaSpinner.getItemAtPosition(i).equals("Select City First!"))
{
buttonAdd.setEnabled(false);
buttonAdd.setVisibility(View.GONE);
}
else
{
buttonAdd.setEnabled(true);
buttonAdd.setVisibility(View.VISIBLE);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Activity.xml
<com.toptoche.searchablespinnerlibrary.SearchableSpinner
android:id="#+id/spinnerCity"
android:layout_width="300dp"
android:layout_height="50dp"
android:layout_marginTop="24dp"
android:entries="#array/city_name"
app:hintText="Select City"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView3" />
<com.toptoche.searchablespinnerlibrary.SearchableSpinner
android:id="#+id/spinnerArea"
android:layout_width="300dp"
android:layout_height="50dp"
android:layout_marginTop="32dp"
app:hintText="Select Area"
app:layout_constraintEnd_toEndOf="#+id/spinnerCity"
app:layout_constraintStart_toStartOf="#+id/spinnerCity"
app:layout_constraintTop_toBottomOf="#+id/spinnerCity" />
Change your create adapter code.
Try this,
ArrayAdapter adapterArea=new ArrayAdapter(getBaseContext(),android.R.layout.simple_spinner_dropdown_item,getResources().getStringArray(R.array.mumbai));
areaSpinner.setAdapter(adapterArea);
In the first spinner the layout set from the library by default but in the second spinner, you are setting it programmatically which is android made and which colors are dependable on a theme of your project so my suggestion for you to change the layout with a customized one.

Listview with checkboxes which saves staes

My application consists of 2 activities.The first activity contains a TextView,if you click on it, you move to the second activity that consists of a ListView and a button Done. The ListView contains TextViews with a CheckBox. If you click on button then it finish activity and returns selected text item. If you go back to the list view the selected checkboxes restored.
Code would be appreciated.
First of all I suggest you to use CheckedTextView control instead of a CheckBox & TextView. CheckedTextView serves as the combination of checkbox and textview and is easy to handle and implement.
Secondly, you should have an ArrayList of boolean of the exact size as the ListView no. of Items. Then you can set the ArrayList items accordingly in the OnListItemClick function of ListView. At any time and anywahere in your code, you can get the reference of your selection of the ListView. Its simple and efficient.
Here is a sample OnListItemClick code:
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
arrCheckBox.set(position, !arrCheckBox.get(position));
CheckedTextView ctvListItem = (CheckedTextView)v.findViewById(R.id.ctvCustomLVRowID);
ctvListItem.setChecked(arrCheckBox.get(position));
}
Here arrCheckBox is a boolean ArrayList which is keeping record of our selection and size of this array is same as no. of ListItems. I hope now you can figure it out.
XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="#+id/LinearLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ListView android:id="#+id/ListView01" android:layout_height="wrap_content"
android:layout_width="fill_parent"></ListView>
</LinearLayout>
Java code:
public class ListViewMultipleChoiceExample extends Activity {
private ListView lView;
private String lv_items[] = { "Android", "iPhone", "BlackBerry",
"AndroidPeople", "J2ME", "Listview", "ArrayAdapter", "ListItem",
"Us", "UK", "India" };
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
lView = (ListView) findViewById(R.id.ListView01);
// Set option as Multiple Choice. So that user can able to select more
// the one option from list
lView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, lv_items));
lView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
}

Combobox in Android

I need something like a combobox in access in android, i want to choose the customer per name, but in the background the id should be chosen. how to do?
In android comboboxes are called spinner. Nevertheless, gnugu has posted in his blog his own implementation of a combobox. http://www.gnugu.com/node/57
A simple example of an spinner would be the following.
First, edit your XML code with something like this
Spinner android:id="#+id/Spinner01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Your java code should include something like this, the options are very intuitive. If you are using eclipse it will suggest you some options
public class SpinnerExample extends Activity {
private String array_spinner[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Here come all the options that you wish to show depending on the
// size of the array.
array_spinner=new String[5];
array_spinner[0]="option 1";
array_spinner[1]="option 2";
array_spinner[2]="option 3";
array_spinner[3]="option 4";
array_spinner[4]="option 5";
Spinner s = (Spinner) findViewById(R.id.Spinner01);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, array_spinner);
s.setAdapter(adapter);
}
}
An alternate solution to the need to link Customer ID to the selected Item.
To have a simple selector with text you cause make use of the array resources
Setup the Spinner in XML
<Spinner android:id="#+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/colors"/>
If you need more data linked with the spinner you can use Objects to populate the spinner.
The default functionality of an ArrayAdapter is to call toString() on any object and pass that to the view.
if (item instanceof CharSequence) {
text.setText((CharSequence)item);
} else {
text.setText(item.toString());
}
You can implement toString() in your object and it will display correctly in the spinner. Then to get the data back from the array you can add a handler onto ItemSelected and get the object back from the seed array or the ArrayAdapter.
ArrayAdapter adapter = new ArrayAdapter(activity, android.R.layout.simple_spinner_item, arrayOfObjects);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
Log.d(arrayOfObjects[position]._id);
}
});

Hide text of Android spinner

I have a spinner with a background image. But when I add array adapter to the spinner, the text is shown on the background image. I want to hide this text. There is also a TextView. My requirement is, when I click the image, the spinner should pop up and when I selects an item, the TextView gets updated with the selected item.
Spinner spin = (Spinner) d.findViewById(R.id.searchCriteria);
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// hide selection text
((TextView)view).setText(null);
// if you want you can change background here
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
Create ghost_text.xml in your layouts folder with this text:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/transparent" />
Then use that file in your adapter like this:
ArrayAdapter<String> your_adapter = new ArrayAdapter<String>(this,
R.layout.ghost_text, your_list);
your_spinner.setAdapter(your_adapter);
You should also be able to use this technique with other resource-based adapters.
Probably you can define a xml-layout file, without any textview in it, and supply it to the adapter for the spinner.
e.g. empty_spinner_item.xml
<ImageView xmlns:android="http..."
android:layout_width=".."
/>
and then use any adapter:
spinner.setAdapter(new SimpleAdapter(this, data, R.layout.empty_spinner_item, ... ));

Categories

Resources