Android adding image to dynamic listview - android

I have already created a dynamic list view that passes text to a SimpleAdapter, however I would like to pass information to make an image appear from the drawable folder. Here is the XML layout for each row:
<ImageView
android:id="#+id/sport_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:padding="2dp"
android:textSize="20dp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right" >
<TextView
android:id="#+id/item_subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dp"
android:textSize="13dp" />
</LinearLayout>
</LinearLayout>
and the bit of code creating the list:
//fill in the list items from the XML document
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("id", XMLfunctions.getValue(e, "fixture_id"));
map.put("sport", XMLfunctions.getValue(e, "sport"));
map.put("teams", XMLfunctions.getValue(e, "team_2") + " v " + XMLfunctions.getValue(e, "team_2"));
mylist.add(map);
}
//Make a new listadapter
ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.fixture, new String[] { "sport", "teams" }, new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
Now at the moment when I pass the string sport it just displays the text such as 'football' in the item_title text view. But as I know what the sport is I would like to be able to display an icon in the sport_icon imageview. An example of the sport icon location would be #drawable/icon_football.
Many thanks.
The answer here was creating a BaseAdapter with the ListView as suggested by Frank below. If anyone else is looking to do the same thing but has no idea where to start I highly recommend watching http://www.youtube.com/watch?v=pVs4qKmenQM. This video is well put together and explains everything you need to know.
:)

You are going to have to extend something like BaseAdapter and check what your position is in getView() and then accordingly set what image you would like to use.
SimpleAdapter only works nice if ALL the items are have the exact same format and it's very simple.
Here is an ok example.
http://thinkandroid.wordpress.com/2010/01/13/custom-baseadapters/
But I would really recommend watching the Romain and Adam's Google IO Video
http://www.youtube.com/watch?v=wDBM6wVEO70

Related

New Game activity in Android: what UI choices?

My Android game project needs a "New Game" activity. The game has a couple of options that should be asked each time a new game is started: the board size and the game seed. I would like to do this in a form resembling the standard "Settings" activity, but with an added "Start" button at the bottom. Given that these things will be chosen every new game, they don't want to be hidden away in the app's Settings activity. So what's the best way to go about this?
Things I've investigated:
Using a custom PreferenceActivity, since the behaviour is almost the same. Since the PreferenceActivity doesn't use layout XML files I can't see a way of adding a button to it.
A Linear layout that includes a ListView and a Button. I've started implementing this, but I can't even find a way to add items to the ListView - the ListView guide in the documentation certainly isn't aimed at a beginner like me! And then the list items need to be interactive to allow options to be selected: this looks like a lot of work to duplicate what PreferenceActivity almost does on its own.
Is there an option that I'm missing? I've spent a couple of hours trying to find an answer in the documentation and in previous questions, but with no progress. If anyone can point me in the right direction I'd be grateful.
Here is some code for you. Hope it will be useful.
You should go by the second way and use LinearLayout (this is main.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">
<ListView
android:id="#+id/lvSimple"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
<Button // describe your start button here/>
</LinearLayout>
Layout for ListView item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/ivImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher">
</ImageView>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<CheckBox
android:id="#+id/cbChecked"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CheckBox">
</CheckBox>
<TextView
android:id="#+id/tvText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginRight="20dp"
android:text="TextView">
</TextView>
</LinearLayout>
</LinearLayout>
Your MainActivity.java:
public class MainActivity extends Activity {
// имена атрибутов для Map
final String ATTRIBUTE_NAME_TEXT = "text";
final String ATTRIBUTE_NAME_CHECKED = "checked";
final String ATTRIBUTE_NAME_IMAGE = "image";
ListView lvSimple;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// data array
String[] texts = { "sometext 1", "sometext 2", "sometext 3",
"sometext 4", "sometext 5" };
boolean[] checked = { true, false, false, true, false };
int img = R.drawable.ic_launcher;
// our data source
ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>(
texts.length);
Map<String, Object> m;
for (int i = 0; i < texts.length; i++) {
m = new HashMap<String, Object>();
m.put(ATTRIBUTE_NAME_TEXT, texts[i]);
m.put(ATTRIBUTE_NAME_CHECKED, checked[i]);
m.put(ATTRIBUTE_NAME_IMAGE, img);
data.add(m);
}
String[] from = { ATTRIBUTE_NAME_TEXT, ATTRIBUTE_NAME_CHECKED,
ATTRIBUTE_NAME_IMAGE };
// array of IDs of Views
int[] to = { R.id.tvText, R.id.cbChecked, R.id.ivImg };
// create adapter
SimpleAdapter sAdapter = new SimpleAdapter(this, data, R.layout.item,
from, to);
// create ListView and set the adapter
lvSimple = (ListView) findViewById(R.id.lvSimple);
lvSimple.setAdapter(sAdapter);
}
}

An ImageView and TextView in a DrawerLayout with Xamarin

I've been trying to bind data to a drawerlayout over the past few days with no luck. I think my issue is the binding of the data and making sure that I have the correct parameters in the right spot. The code is below. For the purposes of this code, I have an array of items that I load from Resources.Array.NavigationItems. Once I have this in a string array, I iterate through the list, create a dictionary with an item, which is the text to be displayed, and an image, which is the image that I want to display. At this time, the image is just load from my resources's drawables. I then create two arrays. These two arrays should map to the necessary from (data in the javalist) and to (the id of the controls to display. When I run the code below, I get the error shown below the code. I am assuming that I have something wrong with my dictionary definitions. Suggestions are appreciated. Quite honestly, I'm not sure that I am creating the Dictionary or the List properly with the correct objects; my skills in translating from java to .net are probably lacking in this area.
_navigationItems = Resources.GetStringArray(Resource.Array.NavigationItems);
var mList = new List<IDictionary<string, object>>();
for(int i=0;i<_navigationItems.Length;i++){
var hm = new Dictionary<String,Object>();
hm.Add("item", _navigationItems[i]);
hm.Add("image", Resource.Drawable.aniswath);
mList.Add(hm);
}
var fromH = new string[]{ "item", "image" };
var toH = new int[] { Resource.Id.title, Resource.Id.icon };
_drawerList.Adapter = new SimpleAdapter (this, mList,
Resource.Layout.custom_drawer_item, fromH, toH);
Here are the contents of my Resource/Layout/custom_drawer_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/icon"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:src="#drawable/aniswath" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#id/icon"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textStyle="bold"
android:gravity="center_vertical"
android:paddingRight="40dp" />
</LinearLayout>
Error message determined from monitor:
04-11 21:40:50.022: E/AndroidRuntime(2515): java.lang.ClassCastException: mono.android.runtime.JavaObject cannot be cast to java.util.Map
04-11 21:40:50.022: E/AndroidRuntime(2515): at android.widget.SimpleAdapter.bindView(SimpleAdapter.java:147)
04-11 21:40:50.022: E/AndroidRuntime(2515): at android.widget.SimpleAdapter.createViewFromResource(SimpleAdapter.java:126)

Listview in Listview -> which adapter should be used (Android)

I have a Listview. In that Listview I have multiple textviews and again a listview.
First I always used the simpleadapter to fill my Listviews with data. But now I have added embedded a listview.
Which Adaplter do I have to use?! Because I think that this is not possible with the simpleadapter.
Main Activity layout:
<ListView
android:id="#+id/lvData"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="#drawable/border_ui"
android:divider="#color/dark_grey"
android:dividerHeight="1dp"
android:padding="4dp" />
Listview (lvData) item layout
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tv_deposit_depiting" />
<ListView
android:id="lvDepositDepitingList"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
I always used the simple adapter that way:
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
for (Deposit deposit : getCurrentList()) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", deposit.getName());
map.put("amount", String.valueOf(deposit.getAmount()));
list.add(map);
}
SimpleAdapter adapter = new SimpleAdapter(this, list,
R.layout.list_item_layout_deposit, new String[] { "name",
"amount" }, new int[] { R.id.tvDepositName,
R.id.tvDepositCurrentMonth });
lvData.setAdapter(adapter);
I think I will have to extend an adapter and write a custom one. If that is what I have to do, which adapter should I extend?
Thanks!
Yes you can create a class extending BaseAdapter and customize the view as you would like, check this link for help and guidelines Custom Adapter Guide

MultiColumn List with drop down spinner

I have a mutlicolumn list in which I also want one of the columns to include a drop down spinner.
My main.xml is: -
<!-- main.xml -->
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/SCHEDULE" android:layout_width="wrap_content" android:layout_height="wrap_content">
</ListView>
My row xml is
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingTop="4dip"
android:paddingBottom="6dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:id="#+id/LEVEL_CELL"
android:layout_width="50dip"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/ACTION_CELL"
android:layout_width="50dip"
android:layout_height="wrap_content"/>
<Spinner
android:id="#+id/fromTables"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Here is my logic: -
super.onCreate(savedInstanceState);
setContentView(R.layout.row);
fromTablesSpinner = (Spinner) findViewById(R.id.fromTables);
setContentView(R.layout.main);
ListView list = (ListView) findViewById(R.id.SCHEDULE);
ArrayList<String> tables = new ArrayList<String>();
tables.add("MARA");
tables.add("MARC");
tables.add("MARD");
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put("level", "1");
map.put("action", "INNER JOIN");
map.put("tables", "MARA");
map.put("tables", "MARC");
mylist.add(map);
map = new HashMap<String, String>();
map.put("level", "2");
map.put("action", "OUTER JOIN");
map.put("tables", "MARA");
map.put("tables", "MARC");
mylist.add(map);
SimpleAdapter mSchedule = new SimpleAdapter(this, mylist, R.layout.row,
new String[] { "level", "action" }, new int[] {
R.id.LEVEL_CELL, R.id.ACTION_CELL });
list.setAdapter(mSchedule);
}
The use of SimpleAdapter does not allow me to bind to a spinner view.
Any help is much appreciated.
Thanks
Martin
You are trying two complicated things at once. Follow these steps:
1) Learn to build a custom adapter which shows more than one type of views in a single list. This will help you to show a spinner in the list.
Links : http://www.ezzylearning.com/tutorial.aspx?tid=1763429
Android ListView with different layouts for each row
2) Learn to handle different view and listeners.
Links: Listview with TextView and Button. RowId of the clicked button (btnButtonOFF.setOnClickListener(new ItemClickListener(cur.getInt(idRow)));)
3) Use Multiple ListViews like you are using.

Listview relativelayout simpleadapter not working

I am trying to display some items in a listview, which is located in a relativelayout.
The whole layout is located in one xml file (main.xml)
The layout has also 2 buttons and 2 more textfields (EditText).
I can`t get it to work, as:
The listview does not show the items
If the listview expands, it duplicates the buttons and textfields present in the layout
can someone please help me?
Here is a part of the layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/kpnback">
<EditText
android:layout_height="wrap_content"
android:layout_width="110dp"
android:id="#+id/editText1"
android:text="edit1"
android:inputType="textMultiLine"
android:layout_below="#+id/lbl_top">
</EditText>
<EditText
android:layout_height="wrap_content"
android:layout_width="110dp"
android:id="#+id/editText2"
android:text="edit2"
android:inputType="textMultiLine"
android:layout_marginLeft="160dp"
android:layout_below="#+id/lbl_top">
</EditText>
<ListView
android:layout_width="fill_parent"
android:layout_height="20dp"
android:id="#+id/kpn"
android:layout_y="350dp"
android:layout_below="#+id/editText1">
</ListView>
</RelativeLayout>
Code for the simpleadapter:
#Override
protected void onPostExecute(String result) {
// create the grid item mapping
ListView kp = (ListView)findViewById(R.id.kpn);
String[] from = new String[] {"col_1", "col_2"};
int[] to = new int[] { R.id.editText1, R.id.editText1 };
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
Document doc = Jsoup.parse(kpn);
Elements tdsFromSecondColumn = doc.select("table.personaltable td:eq(0)");
Elements tdsFromSecondColumn1 = doc.select("table.personaltable td:eq(1)");
for (Element tdFromSecondColumn : tdsFromSecondColumn) {
map.put("col_1", tdFromSecondColumn.text());
fillMaps.add(map);
System.out.println(tdFromSecondColumn.text());
}
for (Element tdFromSecondColumn1 : tdsFromSecondColumn1) {
map.put("col_2", tdFromSecondColumn1.text());
fillMaps.add(map);
System.out.println(tdFromSecondColumn1.text());
}
SimpleAdapter adapter = new SimpleAdapter(AndroidLogin.this, fillMaps, R.layout.main, from, to);
kp.setAdapter(adapter);
1) Do not use "#+id/..." for the layout_below attribute.. Instead use "#id/..."
2) lbl_top is not present inside the RelativeLayout..
3) You'll have to specify layout_toLeftOf or layout_toRightOf, apart from specifying layout_below.
Hope this helps..

Categories

Resources