I'm quite new to android and i'm facing some trouble with managing listviews... I'm generating a ListView properly but all the items in it have the same id, so when I click on any of them, they all do the same thing (which is not what I expect of course...)
I'm loading data from XML URLs, parsing them with a SAX parser. Here is my adapter. My "liste" contains 6 rows of 2 strings separated by "&&&". I then display the listview with :
zadapter.notifyDataSetChanged();
setListAdapter(this.zadapter);
source below
class InfoAdapter extends ArrayAdapter<String> {
private ArrayList<String> items;
public InfoAdapter(Context context, int textViewResourceId, ArrayList<String> items) {
super(context, textViewResourceId, items);
this.items = items;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (Layou开发者_Go百科tInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
}
String liste = items.get(position);
String[] info = liste.split("&&&");
if (liste != null) {
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
if (tt != null) {
tt.setText(info[0]);
}
if(bt != null){
bt.setText(info[1]);
}
Log.e(MY_DEBUG_TAG, "Debug position text"+tt.getId());
}
Log.e(MY_DEBUG_TAG, "Debug position view"+v.getId());
return v;
}
}
Thank you in advance for any help.
In your debug statement, you are having the id of the view which is an identifier and what I believe you want is the index.
To trigger an action that depends on the selected item,
you have to use the setOnItemClickListener
method from the ListView and implement the OnItemClickListener
interface.
The method
public void onItemClick(AdapterView<?> list, View v, int pos, long id)
is the one you need. See the description of the method here
You can request the listview for an index of the selected item and use that, in combination with your listadapter to figure out the actual data of the view.
I think you may want to extend from BaseAdapter
(doesn't require much more work), as ArrayAdapter<T>
's internal list of objects is hidden from your subclass and so your overriden methods are using a completely different list of objects.
See the ArrayAdapter source for more details, especially the private List<T> mObjects
bit.
精彩评论