Listiview with Array - android

How can I create a listview that looks for more than one information in an array?
An example, suppose I have a listview of names from an array, but I still have another array that contains data like age and profession that match each name of the first array.
How could I get more than one information from an array?
Thank you so much.

What is happening when you load an ArrayList into an ArrayAdapter, and then an ArrayAdapter into a ListView, is the ArrayAdapter uses a layout file which contains a TextView. The ArrayAdapter takes the string in each ArrayList element, inflates (creates) a new View with a layout per ArrayList element, and then places the element string in each new layout's TextView.
If you want to customize each row's visual appearance (including what data appears) in your list on the screen, you can make your own custom Adapter by making a new class that extends BaseAdapter and you can make your own layout file that you will inflate in the BaseAdapter. Then find the elements in your layout and assign the data to the elements on a per row basis. Below is example code I wrote for you. I would highly suggest reading the Android documentation on ListViews and Adapters: https://developer.android.com/guide/topics/ui/layout/listview.html
https://developer.android.com/guide/topics/ui/declaring-layout.html#AdapterViews
In my activity OnCreate method (You will need to have a ListView in your layout called list_view or change the name of the ListView in my code):
ArrayList<MyDataModel> myDataModels = new ArrayList<>();
for(int i = 0; i < 50; i++) {
MyDataModel newModel = new MyDataModel("Person" + i, new Random().nextInt() % 100, "Some Profession" + i);
myDataModels.add(newModel);
}
MyListAdapter myListAdapter = new MyListAdapter(myDataModels);
ListView listView = (ListView)findViewById(R.id.list_view);
listView.setAdapter(myListAdapter);
MyDataModel.java:
public class MyDataModel {
public String mName, mProfession;
public int mAge;
public MyDataModel(String name, int age, String profession) {
mName = name;
mAge = age;
mProfession = profession;
}
}
MyListAdapter.java:
public class MyListAdapter extends BaseAdapter {
private ArrayList<MyDataModel> mMyDataModels;
public MyListAdapter(ArrayList<MyDataModel> dataModels) {
mMyDataModels = dataModels;
}
#Override
public int getCount() {
return mMyDataModels.size();
}
#Override
public MyDataModel getItem(int position) {
return mMyDataModels.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_data_model_item, parent, false);
}
MyDataModel model = mMyDataModels.get(position);
((TextView)view.findViewById(R.id.person_name)).setText(model.mName);
((TextView)view.findViewById(R.id.person_age)).setText(String.valueOf(model.mAge));
((TextView)view.findViewById(R.id.person_profession)).setText(model.mProfession);
return view;
}
}

Related

How to display remote images in ListView using BaseAdapter?

I am using the following code to display images on ListView using BaseAdapter .The code displays images from inside drawable folder. But I want to modify the code so it displays remote images from following Array:
String flags[] ={"http://www.website.com/images/usa.png","http://www.website.com/images/china.png","http://www.website.com/images/australia.png","http://www.website.com/images/portugle.png","http://www.website.com/images/norway.png","http://www.website.com/images/new_zealand.png"};
Could an expert show me what part needs to be change.Thanks in advance.
MainActivity.java:
public class MainActivity extends Activity {
ListView simpleList;
String countryList[] = {"USA", "China", "australia", "Portugle", "Norway", "NewZealand"};
int flags[] = {R.drawable.usa, R.drawable.china, R.drawable.australia, R.drawable.portugle, R.drawable.norway, R.drawable.new_zealand};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleList = (ListView) findViewById(R.id.simpleListView);
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), countryList, flags);
simpleList.setAdapter(customAdapter);
simpleList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Hello " + countryList[position], Toast.LENGTH_LONG).show();
}
});
}
}
CustomAdapter.java:
Public class CustomAdapter extends BaseAdapter {
Context context;
String countryList[];
int flags[];
LayoutInflater inflter;
public CustomAdapter(Context applicationContext, String[] countryList, int[] flags) {
this.context = context;
this.countryList = countryList;
this.flags = flags;
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return countryList.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.activity_listview, null);
TextView country = (TextView) view.findViewById(R.id.textView);
ImageView icon = (ImageView) view.findViewById(R.id.icon);
country.setText(countryList[i]);
icon.setImageResource(flags[i]);
return view;
}
}
You need to:
1) Fetch those images in a separate thread, you can use volley, retrofit, robospice for this.
2) On the response of any of those methods from 1) you have to pass the list of values you obtained from the service to your adapter's constructor. You will need to create a POJO for the model, this structure will hold all the elements from the REST webservice.
3) It is recommended to use a viewholder for your listview's adapter, to avoid inflating the views again and again.
The easiest thing to do is use Glide or Picasso:
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.activity_listview, null);
TextView country = (TextView) view.findViewById(R.id.textView);
ImageView icon = (ImageView) view.findViewById(R.id.icon);
country.setText(countryList[i]);
// Assuming flags is now the list of Strings of image urls
GlideApp.with(view.getContext()).load(flags[i]).into(icon);
return view;
}
you can also use some third party library like Picasso or Glide to load images right into your adapter's get view method
Picasso.with(this).load(flags[adapter's
position]).into(imageView);
same in glide.
here is simple tutorial https://www.simplifiedcoding.net/picasso-android-tutorial-picasso-image-loader-library/

Strikethrough an ArrayList<String> item when long pressed

I'm trying to make a simple to-do list where you would long-press an item to mark it as 'done', in which case it will be greyed out and strikethrough.
I'm working on the strikethrough first and found some sample code here creating a strikethrough text in Android? . However the problem is that the setPaintFlags() method only seems to work on TextView whereas the items on my list are String. I can't cast a String to a TextView, and I found a workaround here but apparently it's highly discouraged to do it: Cast String to TextView . Also I looked up SpannableString but it doesn't seem to work for strings of varying length.
So I'm back at square one - is it at all possible to implement what I'm trying to do? Or will I have to store my list items differently instead?
Relevant code:
public class MainActivity extends ActionBarActivity {
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Setting what the ListView will consist of
lvItems = (ListView) findViewById(R.id.lvItems);
readItems();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
lvItems.setAdapter(itemsAdapter);
// Set up remove listener method call
setupListViewListener();
}
//Attaches a long click listener to the listview
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
// Trying to make the onLongClick strikethrough the text
String clickedItem = items.get(pos);
//What do I do here??
// Refresh the adapter
itemsAdapter.notifyDataSetChanged();
writeItems();
// Return true consumes the long click event (marks it handled)
return true;
}
});
}
Let's take a step back and consider your app. You want to show a list of jobs to the user. Each job has a description. And each job has two possible states: 'done' or 'not done'.
So I would like to introduce a class 'Job'
class Job
{
private String mDescription;
private boolean mDone;
public Job(String description)
{
this.mDescription = description;
this.mDone = false;
}
// ... generate the usual getters and setters here ;-)
// especially:
public boolean isDone()
{
return mIsDone;
}
}
This way your ArrayList 'items' becomes be a ArrayList< Job >. Wether a job is done or not will be stored together with its description. This is important because you want to show the current state of the job to the user by changing the look of the UI element, but you need to keep track of the job's state on the data level as well.
The UI element - the TextView - will be configured to present information about the job to the user. One piece of information is the description. The TextView will store this as a String. The other piece of information is the state (done/ not done). The TextView will (in your app) store this by setting the strike-through flag and changing its color.
Because for performance reasons a ListView uses less elements than the data list ('items') contains, you have to write a custom adapter. For brevity's sake, I'm keeping the code very simple, but it's worth the time to read up on the View Holder pattern:
Let's use a layout file 'mytextviewlayout.xml' for the list rows:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/textView"/>
</LinearLayout>
Now the code for the adapter looks like this:
EDIT changed from ArrayAdapter to BaseAdapter and added a view holder (see comments):
public class MyAdapter extends BaseAdapter
{
private ArrayList<Job> mDatalist;
private int mLayoutID;
private Activity mCtx;
private MyAdapter(){} // the adapter won't work with the standard constructor
public MyAdapter(Activity context, int resource, ArrayList<Job> objects)
{
super();
mLayoutID = resource;
mDatalist = objects;
mCtx = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = mCtx.getLayoutInflater();
rowView = inflater.inflate(mLayoutID, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tvDescription = (TextView) rowView.findViewById(R.id.textView);
rowView.setTag(viewHolder);
}
ViewHolder vholder = (ViewHolder) rowView.getTag();
TextView tvJob = vholder.tvDescription;
Job myJob = mDatalist.get(position);
tvJob.setText(myJob.getJobDescription());
if (myJob.isDone())
{
// apply changes to TextView
tvJob.setPaintFlags(tvJob.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
tvJob.setTextColor(Color.GRAY);
}
else
{
// show TextView as usual
tvJob.setPaintFlags(tvJob.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
tvJob.setTextColor(Color.BLACK); // or whatever is needed...
}
return rowView;
}
#Override
public int getCount()
{
return mDatalist.size();
}
#Override
public Object getItem(int position)
{
return mDatalist.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
static class ViewHolder
{
public TextView tvDescription;
}
}
Due to the changed adapter,
in the MainActivity, you have to declare 'items' and 'itemsAdapter' as follows:
private ArrayList<Job> items;
private MyAdapter itemsAdapter;
...and in your 'onCreate()' method, you write:
itemsAdapter = new MyAdapter<String>(this, R.layout.mytextviewlayout, items);
Don't forget to change the 'readItems()' and 'writeItems()' methods because 'items' now is a ArrayList< Job >.
Then, finally, the 'onItemLongClick()' method:
EDIT use 'parent.getItemAtPosition()' instead of 'items.get()', see comments
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
{
// items.get(position).setDone(true);
Object o = parent.getItemAtPosition(position);
if (o instanceof Job)
{
((Job) o).setDone(true);
}
// and now indeed the data set has changed :)
itemsAdapter.notifyDataSetChanged();
writeItems();
return true;
}

custom adapter isn't showing any items

This is a follow on from an earlier question: ImageButton within row of ListView android not working
But after suggestions from SO gurus it has been suggested I post a new question.
The issue is that I have a custom adapter that is not showing any data. I have looked into other questions, but it didn't provide a solution.
In my Main Activity I have a couple of buttons, one of them: ToDo, should create a row that displays data from a SQLite database, and depending on some factors (dates mainly), it shows a type of traffic light that is stored as a drawable.
Part of the Items in this Row is an Image Button that I want the user to be able to click and the image should change. The user should be able also to click on the actual row and a new activity starts.
The issue I have is that NO DATA is being displayed.
So, here is my code:
public class MainActivity extends Activity {
// definitions etc ...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// definitions etc ...
}
public void ToDo(View v){ // the user has clicked in the ToDo button
IgroDatabaseHelper helper = new IgroDatabaseHelper(getBaseContext()); // create instance of SQLIte database
numRows = helper.NumEntries("ToDo"); // Get the number of rows in table
int i = 1;
ArrayList<RowItem> rowItems = new ArrayList<>();
RowItem myItem1;
while (i <= numRows){
// get items from database
// depending on value select different drawable
// put data into List Array of RowItem
myItem1 = new RowItem(TheWhat, R.drawable.teamworka, R.drawable.redtrafficlight, R.drawable.checkbox, TheWhenBy);
rowItems.add(myItem1);
//
i = i+ 1;
}
ListView yourListView = (ListView) findViewById(R.id.list);
CustomListViewAdapter customAdapter = new CustomListViewAdapter(this, R.layout.todo_row, rowItems);
yourListView.setAdapter(customAdapter);
}
The CustomListViewAdapter looks like this:
public class CustomListViewAdapter extends ArrayAdapter<RowItem> {
Context context;
ArrayList<RowItem> _rowItems;
public CustomListViewAdapter(Context context, int resourceId,
ArrayList<RowItem> rowItems) {
super(context, resourceId);
this.context = context;
_rowItems = rowItems;
System.out.println("I am in the custom Adapter class "+ _rowItems);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
System.out.println("This is the get view");
View row = convertView;
RowItem item = _rowItems.get(position);
// you can now get your string and drawable from the item
// which you can use however you want in your list
String columnName = item.getColumnName();
int drawable = item.getDrawable();
if (row == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = mInflater.inflate(R.layout.todo_row, parent, false);
}
ImageButton chkDone = (ImageButton) row.findViewById(R.id.chkDone);
chkDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentRow = (View) v.getParent();
ListView listView = (ListView) parentRow.getParent();
final int position = listView.getPositionForView(parentRow);
System.out.println("I am in position "+ position);
}
});
return row;
}
}
The RowItem Class looks like:
public class RowItem {
private String _heading;
private int _icon;
private int _lights;
private int _chkdone;
private String _date;
public RowItem(String heading, int icon, int lights, int chkDone, String date) {
_heading = heading;
_icon = icon;
_lights = lights;
_chkdone = chkDone;
_date = date;
System.out.println("adding stuff to my rows");
System.out.println("my column Name is " + heading);
System.out.println("My drawable int is "+ icon);
}
public String getColumnName() {
System.out.println("column Names is "+ _heading);
return _heading;
}
public int getDrawable() {
return _icon;
}
public int getLights(){
return _lights;
}
public int getchkDone(){
return _chkdone;
}
public String getDate(){
return _date;
}
}
I am obviously missing something, as I mentioned earlier, no data gets shown. I know that there are 2 row items that get passed to the CustomListViewAdapter. But I also know that the View getView inside the CustomListViewAdapter does not actually get called.
I hope I have put enough information/code, but if you feel I need to explain something further, please say.
Thanking all very much in advance!
I don't see a getCount() method. You should be overriding it like this:
#Override
public int getCount() {
return _rowItems.getCount();
}
Alternatively, calling super(context, resourceId, rowItems); should also fix it.
Your ListView thinks there are no items to display. If you are using your own array, you must override the getCount() method to indicate the number of items you want to display.

Android add items to arraylist using custom class

I'm trying to add items to an arraylist using this class template:
public class Template {
public String username;
public String email;
}
Here's the whole code:
public void JsonToArrayList(JSONArray myJsonArray) throws JSONException
{
ArrayList<Template> listItems = new ArrayList<Template>();
JSONObject jo = new JSONObject();
Template tem = new Template();
ListView lv = (ListView) findViewById(R.id.listView1);
for(int i = 0; i<myJsonArray.length(); i++)
{
jo = myJsonArray.getJSONObject(i);
tem.username = jo.getString("username");
tem.email = jo.getString("user_email");
listItems.add(tem);
Log.e("Ninja Archives", tem.username);
}
// This is the array adapter, it takes the context of the activity as a first // parameter, the type of list view as a second parameter and your array as a third parameter
ArrayAdapter<Template> arrayAdapter = new ArrayAdapter<Template>(this,android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(arrayAdapter);
}
The problem is, instead of filling my listview with nice username and email strings, it's filling up with items like this:
com.android.ninjaarchives.
Template#40585690
I think somewhere along the line I have become lost, but I've been trying all sorts for ages now and getting nowhere. Can anyone point me in the right direction?
Thanks for any help.
Note: not really sure what's going on with the code; it doesn't appear to be pasting correctly.
Use below code, it can be a solution for you
public void JsonToArrayList(JSONArray myJsonArray) throws JSONException
{
ArrayList<Template> listItems = new ArrayList<Template>();
JSONObject jo = new JSONObject();
Template tem = new Template();
ListView lv = (ListView) findViewById(R.id.listView1);
String listItemString[] = new String[myJsonArray.length];
for(int i = 0; i<myJsonArray.length(); i++)
{
jo = myJsonArray.getJSONObject(i);
tem.username = jo.getString("username");
tem.email = jo.getString("user_email");
listItemString[i] = tem.username +" - " + tem.email; // u can change it according to ur need.
listItems.add(tem);
Log.e("Ninja Archives", tem.username);
}
// This is the array adapter, it takes the context of the activity as a first // parameter, the type of list view as a second parameter and your array as a third parameter
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItemString);
lv.setAdapter(arrayAdapter);
}
But better to write Custom adapter by extending BaseAdapter, and do listItem handling in getView method here is one simple tutorial
Take a class extending Base
private class CustomAdapter extends BaseAdapter
{
LayoutInflater inflater;
public CustomAdapter(Context context)
{
inflater = LayoutInflater.from(context);
}
public int getCount()
{
return listItems.size();
}
public Object getItem(int position)
{
return listItems.get(position);
}
public long getItemId(int position)
{
return position;
}
public View getView(final int position, View convertView,ViewGroup parent)
{
//if(convertView==null)
//convertView = inflater.inflate(R.layout.listlayout, parent, false);
Template data = (Template) getItem(position);
TextView v=new TextView(context);
v.setText(data.name);
return v;
}
}
and set adapter to your listview
lv.setAdapter(new CustomAdapter(this));
In this case you have to use a custom adapter (that extends from ArrayAdapter) and override the getView method to display in a custom layout the username and the email.

Android Spinner databind using array list

I have a array list like this:
private ArrayList<Locations> Artist_Result = new ArrayList<Location>();
This Location class has two properties: id and location.
I need to bind my ArrayList to a spinner. I have tried it this way:
Spinner s = (Spinner) findViewById(R.id.SpinnerSpcial);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, Artist_Result);
s.setAdapter(adapter);
However, it shows the object's hexadecimal value. So I think I have to set display the text and value for that spinner controller.
The ArrayAdapter tries to display your Location-objects as strings (which causes the Hex-values), by calling the Object.toString()-method. It's default implementation returns:
[...] a string consisting of the name of the class of which the object
is an instance, the at-sign character `#', and the unsigned
hexadecimal representation of the hash code of the object.
To make the ArrayAdadpter show something actually useful in the item list, you can override the toString()-method to return something meaningful:
#Override
public String toString(){
return "Something meaningful here...";
}
Another way to do this is, to extend BaseAdapter and implement SpinnerAdapter to create your own Adapter, which knows that the elements in your ArrayList are objects and how to use the properties of those objects.
[Revised] Implementation Example
I was playing around a bit and I managed to get something to work:
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create and display a Spinner:
Spinner s = new Spinner(this);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
);
this.setContentView(s, params);
// fill the ArrayList:
List<Guy> guys = new ArrayList<Guy>();
guys.add(new Guy("Lukas", 18));
guys.add(new Guy("Steve", 20));
guys.add(new Guy("Forest", 50));
MyAdapter adapter = new MyAdapter(guys);
// apply the Adapter:
s.setAdapter(adapter);
// onClickListener:
s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
/**
* Called when a new item was selected (in the Spinner)
*/
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Guy g = (Guy) parent.getItemAtPosition(pos);
Toast.makeText(
getApplicationContext(),
g.getName()+" is "+g.getAge()+" years old.",
Toast.LENGTH_LONG
).show();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
});
}
/**
* This is your own Adapter implementation which displays
* the ArrayList of "Guy"-Objects.
*/
private class MyAdapter extends BaseAdapter implements SpinnerAdapter {
/**
* The internal data (the ArrayList with the Objects).
*/
private final List<Guy> data;
public MyAdapter(List<Guy> data){
this.data = data;
}
/**
* Returns the Size of the ArrayList
*/
#Override
public int getCount() {
return data.size();
}
/**
* Returns one Element of the ArrayList
* at the specified position.
*/
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int i) {
return i;
}
/**
* Returns the View that is shown when a element was
* selected.
*/
#Override
public View getView(int position, View recycle, ViewGroup parent) {
TextView text;
if (recycle != null){
// Re-use the recycled view here!
text = (TextView) recycle;
} else {
// No recycled view, inflate the "original" from the platform:
text = (TextView) getLayoutInflater().inflate(
android.R.layout.simple_dropdown_item_1line, parent, false
);
}
text.setTextColor(Color.BLACK);
text.setText(data.get(position).name);
return text;
}
}
/**
* A simple class which holds some information-fields
* about some Guys.
*/
private class Guy{
private final String name;
private final int age;
public Guy(String name, int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
}
I fully commented the code, if you have any questions, don't hesitate to ask them.
Simplest Solution
After scouring different solutions on SO, I found the following to be the simplest and cleanest solution for populating a Spinner with custom Objects. Here's the full implementation:
Location.java
public class Location{
public int id;
public String location;
#Override
public String toString() {
return this.location; // What to display in the Spinner list.
}
}
res/layout/spinner.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="wrap_content"
android:padding="10dp"
android:textSize="14sp"
android:textColor="#FFFFFF"
android:spinnerMode="dialog" />
res/layout/your_activity_view.xml
<?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">
<Spinner
android:id="#+id/location" />
</LinearLayout>
In Your Activity
// In this case, it's a List of Locations, but it can be a List of anything.
List<Location> locations = Location.all();
ArrayAdapter locationAdapter = new ArrayAdapter(this, R.layout.spinner, locations);
Spinner locationSpinner = (Spinner) findViewById(R.id.location);
locationSpinner.setAdapter(locationAdapter);
// And to get the actual Location object that was selected, you can do this.
Location location = (Location) ( (Spinner) findViewById(R.id.location) ).getSelectedItem();
Thanks to Lukas' answer above (below?) I was able to get started on this, but my problem was that his implementation of the getDropDownView made the dropdown items just a plain text - so no padding and no nice green radio button like you get when using the android.R.layout.simple_spinner_dropdown_item.
So as above, except the getDropDownView method would be:
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(android.R.layout.simple_spinner_dropdown_item, null);
}
TextView textView = (TextView) convertView.findViewById(android.R.id.text1);
textView.setText(items.get(position).getName());
return convertView;
}
Well, am not gonna confuse with more details.
Just create your ArrayList and bind your values like this.
ArrayList tExp = new ArrayList();
for(int i=1;i<=50;i++)
{
tExp.add(i);
}
Assuming that you have already a spinner control on your layout say with id, spinner1. Add this code below.
Spinner sp = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adp1=new ArrayAdapter<String>this,android.R.layout.simple_list_item_1,tExp);
adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adp1);
All the above code goes under your onCreate function.
Thank Lukas, you help me a lot.
I d'like to improve your answer.
If you just want to access the selected item later, you can use this :
Spinner spn = (Spinner) this.findViewById(R.id.spinner);
Guy oGuy = (Guy) spn.getSelectedItem();
So you don't have to use the setOnItemSelectedListener() in your initialisation :)

Categories

Resources