I'm trying to create a spinner with default empty selected item, but it displays the first item from the choices of spinner. If I add null value to my string, which is the source of choices in spinner, then after opening spinner that empty row is displayed. How should I do it? Here's code I'm using:
String[] ch = {"Session1", "Session2", "Session3"};
Spinner sp = (Spinner)findViewById(R.id.spinner1);
TextView sess_name = findViewById(R.id.sessname);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,ch);
sp.setAdapter(adapter);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener({
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
sess_name.setText(ch[index]);
Toast.makeText(getBaseContext(), "You have selected item : " + ch[index], Toast.LENGTH_SHORT).show();
}
Barak's solution have a problem. When you select the first item, Spinner won't call OnItemSelectedListener's onItemSelected() and refresh the empty content because the previous position and selection position both is 0.
First put a empty string at the begin of your string array:
String[] test = {" ", "one", "two", "three"};
Second build adapter, don't modify getView(), modify getDropDownView(). Set the empty View's height to 1px.
public class MyArrayAdapter extends ArrayAdapter<String> {
private static final int ITEM_HEIGHT = ViewGroup.LayoutParams.WRAP_CONTENT;
private int textViewResourceId;
public MyArrayAdapter(Context context,
int textViewResourceId,
String[] objects) {
super(context, textViewResourceId, objects);
this.textViewResourceId = textViewResourceId;
}
#Override
public View getDropDownView(int position, View convertView, #NonNull ViewGroup parent) {
TextView textView;
if (convertView == null) {
textView = (TextView) LayoutInflater.from(getContext())
.inflate(textViewResourceId, parent, false);
} else {
textView = (TextView) convertView;
}
textView.setText(getItem(position));
if (position == 0) {
ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
layoutParams.height = 1;
textView.setLayoutParams(layoutParams);
} else {
ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
layoutParams.height = ITEM_HEIGHT;
textView.setLayoutParams(layoutParams);
}
return textView;
}
}
I'm a little late to the party, but here is what I did to solve this.
If the user cancels out of selecting an initial item the spinner will retain the initial empty state. Once an initial item has been selected it works as 'normal'
Works on 2.3.3+, I have not tested on 2.2 and below
First, create an adapter class...
public class EmptyFirstItemAdapter extends ArrayAdapter<String>{
//Track the removal of the empty item
private boolean emptyRemoved = false;
/** Adjust the constructor(s) to fit your purposes. */
public EmptyFirstitemAdapter(Context context, List<String> objects) {
super(context, android.R.layout.simple_spinner_item, objects);
setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
#Override
public int getCount() {
//Adjust the count based on the removal of the empty item
if(emptyRemoved){
return super.getCount();
}
return super.getCount()-1;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
if(!emptyRemoved){
// Remove the empty item the first time the dropdown is displayed.
emptyRemoved = true;
// Set to false to prevent auto-selecting the first item after removal.
setNotifyOnChange(false);
remove(getItem(0));
// Set it back to true for future changes.
setNotifyOnChange(true);
}
return super.getDropDownView(position, convertView, parent);
}
#Override
public long getItemId(int position) {
// Adjust the id after removal to keep the id's the same as pre-removal.
if(emptyRemoved){
return position +1;
}
return position;
}
}
Here is the string array I used in strings.xml
<string-array name="my_items">
<item></item>
<item>Item 1</item>
<item>Item 2</item>
</string-array>
Next, add an OnItemSelectedListener to your Spinner...
mSpinner = (Spinner) mRootView.findViewById(R.id.spinner);
String[] opts = getResources().getStringArray(R.array.my_items);
//DO NOT set the entries in XML OR use an array directly, the adapter will get an immutable List.
List<String> vals = new ArrayList<String>(Arrays.asList(opts));
final EmptyFirstitemAdapter adapter = new EmptyFirstitemAdapter(getActivity(), vals);
mSpinner.setAdapter(adapter);
mSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
//Track that we have updated after removing the empty item
private boolean mInitialized = false;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(!mInitialized && position == 0 && id == 1){
// User selected the 1st item after the 'empty' item was initially removed,
// update the data set to compensate for the removed item.
mInitialized = true;
adapter.notifyDataSetChanged();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Nothing to do
}
});
It may not be a 'perfect' solution, but I hope it helps someone.
After some thinking, I believe I've come up with a method to achieve your goal. It involves creating a
custom adapter and setting/maintaining a flag to determine if an item from the spinner has been selected.
Using this method you do not need to create/use false data (your empty string).
Basically, the adapters getView method sets the text for the closed spinner. So if you override that
and set a conditional in there, you can have a blank field on startup and after you make a selection have
it appear in the closed spinner box. The only thing is you need to remember to set the flag whenever you
need to see the value in the closed spinner.
I've created a small example program (code below).
Note that I only added the single constructor I needed for my example. You can implement all the standard
ArrayAdapter constructors or only the one(s) you need.
SpinnerTest.java
public class SpinnerTestActivity extends Activity {
private String[] planets = { "Mercury", "Venus", "Earth", "Mars",
"Jupiter", "Saturn", "Uranus", "Neptune" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
CustomAdapter adapter = new CustomAdapter(this, // Use our custom adapter
android.R.layout.simple_spinner_item, planets);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
CustomAdapter.flag = true; // Set adapter flag that something
has been chosen
}
});
}
}
CustomAdapter.java
public class CustomAdapter extends ArrayAdapter {
private Context context;
private int textViewResourceId;
private String[] objects;
public static boolean flag = false;
public CustomAdapter(Context context, int textViewResourceId,
String[] objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.textViewResourceId = textViewResourceId;
this.objects = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = View.inflate(context, textViewResourceId, null);
if (flag != false) {
TextView tv = (TextView) convertView;
tv.setText(objects[position]);
}
return convertView;
}
}
Here is what I use. It properly handles null (empty) selection in a generic manner. It works with any model class T, as long as class T properly implements toString(), to display the text shown in the spinner, and equals(), so that items may be selected by reference rather than by positional index.
package com.10xdev.android.components;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* A spinner where no selection is possible, and other enhancements.
* requires model class to properly implement Object.equals, with semantic comparaison (such as id comparaison)
* and a proper toString(), whose result will be displayed in the spinner
*
* #author tony.benbrahim
*/
public class EnhancedSpinner<T> extends Spinner {
private final EnhanceArraySpinnerAdapter<T> spinnerAdapter;
private final List<T> items = new ArrayList<>();
private T selected = null;
public EnhancedSpinner(final Context context, final AttributeSet attributeSet) {
super(context, attributeSet);
spinnerAdapter = new EnhanceArraySpinnerAdapter<>(context, items);
setAdapter(spinnerAdapter);
}
/**
* sets the items to be displayed
*
* #param items
*/
public void setItems(final List<T> items) {
this.items.clear();
//very iffy, but works because of type erasure
this.items.add((T) "");
this.items.addAll(items);
spinnerAdapter.notifyDataSetChanged();
updateSelected();
}
/**
* set the selected item. this may be called before or after setting items
*
* #param item the item to select, or null to clear the selection
*/
public void setSelected(final T item) {
this.selected = item;
updateSelected();
}
/**
* gets the selected item, or null if no item is selected
*
* #return
*/
#Override
public T getSelectedItem() {
return getSelectedItemPosition() != 0 ? (T) super.getSelectedItem() : null;
}
/**
* set the error message for the select
*
* #param errorMessage
*/
public void setError(final String errorMessage) {
final TextView errorText = (TextView) getSelectedView();
errorText.setError("error");
errorText.setTextColor(Color.RED);
errorText.setText(errorMessage);
}
private void updateSelected() {
if (selected == null) {
setSelection(0);
} else {
for (int i = 1; i < items.size(); ++i) {
if (selected.equals(items.get(i))) {
setSelection(i);
break;
}
}
}
}
private class EnhanceArraySpinnerAdapter<T> extends ArrayAdapter<T> {
private final LayoutInflater inflater;
public EnhanceArraySpinnerAdapter(final Context context, final List<T> objects) {
super(context, android.R.layout.simple_spinner_item, objects);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getDropDownView(final int position, final View convertView, final ViewGroup parent) {
final TextView textView = convertView != null ? (TextView) convertView
: (TextView) inflater.inflate(android.R.layout.simple_spinner_item, parent, false);
final Object item = getItem(position);
textView.setText(item.toString());
final ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
layoutParams.height = position == 0 ? 1 : LayoutParams.WRAP_CONTENT;
textView.setLayoutParams(layoutParams);
return textView;
}
}
}
You have to put the first element of the spinner empty, or with an string indicating that nothing is selected like the following:
String[] ch= {"","Session1", "Session2", "Session3"};
or
String[] ch= {"Nothing selected", "Session1", "Session2", "Session3"};
hope to help
Related
I made a scroll list with multiple items. When I click on one item the color of the background of that item changes.
public class MyList extends Activity {
PackageManager packMan;
public static ArrayList<ItemList> list;
private ArrayAdapter<ItemList> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.items);
init();
create();
addClickListener();
}
public void init(){
if(list==null) {
list = new ArrayList<ItemList>();
packMan = getPackageManager();
Intent i = new Intent(Intent.ACTION_MAIN, null);
i.addCategory("com.example.example");
List<ResolveInfo> items = packMan.queryIntentActivities(i, 0);
for (ResolveInfo ri : items) {
ItemList item = new ItemList();
item.addName((String) ri.loadLabel(packMan));
item.addNamePackage(ri.activityInfo.name);
item.addIcon(ri.activityInfo.loadIcon(packMan));
list.add(item);
}
}
}
private void create(){
v = (ListView)findViewById(R.id.list);
adapter = new ArrayAdapter<ItemList>(this, R.layout.items, list) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.items, null);
ImageView icon = (ImageView) convertView.findViewById(R.id.icon);
icon.setImageDrawable(list.get(position).getIcon());
TextView name = (TextView) convertView.findViewById(R.id.name);
name.setText(list.get(position).getName());
}
return convertView;
}
};
v.setAdapter(adapter);
}
private void addClickListener(){
v.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
av.getChildAt(pos).setBackgroundColor(Color.parseColor("#DDFFFF"));
}
});
}
}
I am having a problem. When I select one item others are selected automatically.
How can I resolve this problem? Thanks.
From your code it seems that on click on an item you set its background to color DDFFFF, but you never switch them back to their original color once "unselected" . You can either:
keep track of the only selected item, and switch it back to white before coloring the new one (good if you only have 1 selected item at any time)
Whiten everyone on click, and then color the new one
Keep track of the state of each item with a list of booleans (active/inactive), and then override the draw loop to color according to their state
I have created an Adapter arraylist that uses a LayoutInflater so images keep ratio. I am trying to perform a simple toast of the item title selected i.e "Beef".
Everthing workd as expected except I am getting an output from toast of, example
test com.sweatboxbbq.www.sweatboxbbq.Kansas City$MyAdaptor$Item#42aa9398
I know I am requesting a string value of and I'm getting it, but from the code, I can't figure out how to get what I want.
I want to capture the title only so I can toast it back (for now then aventually do something else).
Example items.add(new Item( beef, R.drawable.mine_beef)); I would get a string value of "beef"
Maybe I can id the title's of these array items somehow and pull them from there with the onclick method?
below is my Java code
public class KansasCity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.kansas_city);
final GridView gridView = (GridView) findViewById(R.id.meat_choice);
gridView.setAdapter(new MyAdapter(this));
//on click starts here
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> MyAdapter, View v, int position, long id)
{
String flavorPicked = "" +
String.valueOf(MyAdapter.getItemAtPosition(position));
Toast.makeText(KansasCity.this, "Test " + flavorPicked,
Toast.LENGTH_LONG).show();
}
});
}
//gridview
public class MyAdapter extends BaseAdapter {
public List<Item> items = new ArrayList<Item>();
private LayoutInflater inflater;
public MyAdapter(Context context) {
inflater = LayoutInflater.from(context);
items.add(new Item( "Beef", R.drawable.mine_beef));
items.add(new Item("Chicken", R.drawable.mine_chicken));
items.add(new Item("Swine", R.drawable.mine_pork));
items.add(new Item("Fish", R.drawable.mine_pork));
items.add(new Item("Turkey", R.drawable.mine_pork));
items.add(new Item("Sauce", R.drawable.mine_pork));
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return items.get(i).drawableId;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
ImageView picture;
TextView name;
if (v == null) {
v = inflater.inflate(R.layout.gridview_item, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView) v.getTag(R.id.picture);
name = (TextView) v.getTag(R.id.text);
Item item = (Item) getItem(i);
picture.setImageResource(item.drawableId);
name.setText(item.name);
return v;
}
private class Item {
final String name;
final int drawableId;
Item(String name, int drawableId) {
this.name = name;
this.drawableId = drawableId;
}
}
}
}
Thank you for any help.
you can either override toString() in your Item class and make it return the String you want to display, or make the member name of Item public, and use it like
String flavorPicked = ((Item)MyAdapter.getItemAtPosition(position)).name;
Please remove the " after flavorPicked
Toast.makeText(KansasCity.this, "Test " + flavorPicked",
Toast.LENGTH_LONG).show();
I use simple_list_item_1 to show list in my app. I want to change the list so each element in list will have an image + radio button in addition to his text which taken from Const.practisesList.
This is the code now :
ListAdapter listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Const.practisesList);
final ListView tests_list = (ListView)findViewById(R.id.tests_list);
tests_list.setAdapter(listAdapter);
tests_list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
switch(position){
case Const.TEST_TYPE1_MATH:
p = practiseCreator(1)
break;
case Const.TEST_TYPE4_INSTRUCTIONS:
p = practiseCreator(4)
break;
}
}
});
What is the way to do it?
thanks
Create custom layout for your row. Implement custom adapter extended from ArrayAdapter.
private class SchemeAdapter extends ArrayAdapter<String> {
private int layout;
public SchemeAdapter(final Context context, final List<String> objects) {
//row layout id, content view id
super(context, R.layout.list_row_practice, R.id.list_row_practice_name,
objects);
layout = R.layout.list_row_practice;
}
#Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
final View row =
(convertView == null) ? getLayoutInflater().inflate(layout, parent, false) :
convertView;
if (row != null) {
final TextView name = (TextView) row.findViewById(R.id.list_row_practice_name);
//set here your text, image view src and radio button value.
}
return row;
}
}
I have a ListView of Spinners I'm trying to get the selected values out of. Some of the Spinners have the first selection automatically selected if there is only 1 item in the list, so I feel
setOnItemSelectedListener
won't necessarily work? Either way, I'm unsure how to code this scenario. Even if I had the listener coded correctly, How do I use it in my class to work with the adapter?
CustomAdapter
public class CustomPLNViewAdapter extends BaseAdapter{
private static ArrayList<ArrayList<String>> partLotNumbersArrayList;
private static ArrayList<String> partNames;
private LayoutInflater mInflater;
private Context myContext;
public CustomPLNViewAdapter(Context context, ArrayList<ArrayList<String>> results, ArrayList<String> parts){
partLotNumbersArrayList = results;
partNames = parts;
mInflater = LayoutInflater.from(context);
myContext = context;
}
#Override
public int getCount() {
return partLotNumbersArrayList.size();
}
#Override
public Object getItem(int position) {
return partLotNumbersArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.view_assembly_parts, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView.findViewById(R.id.partName);
holder.spinner = (Spinner) convertView.findViewById(R.id.LotNumbers);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtName.setText(partNames.get(position));
ArrayAdapter<String> adp1=new ArrayAdapter<String>(myContext, android.R.layout.simple_list_item_1, partLotNumbersArrayList.get(position));
adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//set the adapter to the spinnner
holder.spinner.setAdapter(adp1);
//if there is only one other part besides "" then set that as default part
if(partLotNumbersArrayList.get(position).size() == 2){
holder.spinner.setSelection(1);
}
return convertView;
}
static class ViewHolder {
TextView txtName;
Spinner spinner;
}
}
Where I am calling the code. Obviously I get an error here because an ArrayList cannot be cast to Spinner, but I'm unsure how to get the View of the Adapter and then the subsequent spinner?
// save button click event
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Log.d("lv count", Integer.toString(lv.getCount()));
//iterate through listview,
for(int i = 0; i < lv.getCount(); i++){
Spinner temp = (Spinner) lv.getItemAtPosition(i);
Log.d("lv isItemCheck", temp.getSelectedItem().toString());
}
//check to make sure all items have been selected
if(!checkAllParts()){
Toast.makeText(getApplicationContext(), "Please Select All List Items", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "All items have been selected", Toast.LENGTH_SHORT).show();
}
//go back to previous intent, return 100 that saving succeeded
//close intent
}
});
Is there a working example out there that demonstrates how to append additional rows in ListView dynamically?
For example:
you are pulling RSS feeds from
different domains
you then display the first 10 items
in the ListView (while you have
other threads running in the
background continue pulling feeds)
you scroll and reach the bottom of
the List and click at a button to
view more items
the ListView will then get appended
with additional 10 items, which
makes 20 items now in total.
Any advice how to accomplish this?
Nicholas
To add new item to your list dynamically you have to get adapter class from your ListActivity and simply add new elements. When you add items directly to adapter, notifyDataSetChanged is called automatically for you - and the view updates itself. You can also provide your own adapter (extending ArrayAdapter) and override the constructor taking List parameter. You can use this list just as you use adapter, but in this case you have to call adapter.notifyDataSetChanged() by yourself - to refresh the view.
Please, take a look at the example below:
public class CustomList extends ListActivity {
private LayoutInflater mInflater;
private Vector<RowData> data;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
RowData rd = new RowData("item1", "description1");
data.add(rd);
rd = new RowData("item2", "description2");
data.add(rd);
rd = new RowData("item2", "description3");
data.add(rd);
CustomAdapter adapter = new CustomAdapter(this, R.layout.custom_row,R.id.item, data);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
CustomAdapter adapter = (CustomAdapter) parent.getAdapter();
RowData row = adapter.getItem(position);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(row.mItem);
builder.setMessage(row.mDescription + " -> " + position );
builder.setPositiveButton("ok", null);
builder.show();
}
/**
* Data type used for custom adapter. Single item of the adapter.
*/
private class RowData {
protected String mItem;
protected String mDescription;
RowData(String item, String description){
mItem = item;
mDescription = description;
}
#Override
public String toString() {
return mItem + " " + mDescription;
}
}
private class CustomAdapter extends ArrayAdapter<RowData> {
public CustomAdapter(Context context, int resource,
int textViewResourceId, List<RowData> objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
//widgets displayed by each item in your list
TextView item = null;
TextView description = null;
//data from your adapter
RowData rowData= getItem(position);
//we want to reuse already constructed row views...
if(null == convertView){
convertView = mInflater.inflate(R.layout.custom_row, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
//
holder = (ViewHolder) convertView.getTag();
item = holder.getItem();
item.setText(rowData.mItem);
description = holder.getDescription();
description.setText(rowData.mDescription);
return convertView;
}
}
/**
* Wrapper for row data.
*
*/
private class ViewHolder {
private View mRow;
private TextView description = null;
private TextView item = null;
public ViewHolder(View row) {
mRow = row;
}
public TextView getDescription() {
if(null == description){
description = (TextView) mRow.findViewById(R.id.description);
}
return description;
}
public TextView getItem() {
if(null == item){
item = (TextView) mRow.findViewById(R.id.item);
}
return item;
}
}
}
You can extend the example above and add "more" button - which just add new items to your adapter (or vector). Regards!