开发者

Passing Extras to listView ArrayAdapter

I have 2 buttons, when you click them, it launches a new listView activity. Before it starts the activity, I make a bundle, putString depending on which button was clicked and putExtras.

In the listView activity, I have two string arrays. I want the ArrayAdapter to getExtras and read the variable so I know which button was pressed to get there and then I'll know which string array to load into the ArrayAdapter.

Here is my idea but the ArrayAdapter doesn't accept the string, even though s = the name of one of the string arrays. Also, I'm not sure if I'm approaching this in the best way.

Bundle b = this.getIntent().getExtras();
    String s = b.getString("TEXT");
    setListAdapter(new ArrayAdapter<Str开发者_StackOverflow中文版ing>(this, R.layout.list_item, s));


The array adapter takes a list of objects as a third parameter as the documentation on public constructors suggests (Source Developer Android):

Constructor
ArrayAdapter(Context context, int textViewResourceId, T[] objects)
Constructor
ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)
Constructor
ArrayAdapter(Context context, int textViewResourceId, List<T> objects)
Constructor
ArrayAdapter(Context context, int resource, int textViewResourceId, List<T> objects)

So you just need to encapsulate your String in an array (even if you have only one string to display).

ArrayList<String> arr = new ArrayList<String>();
arr.add(s);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, arr));

EDIT Ok. Why don't you try a very basic if-else statement? Like:

ArrayList<String> arrButton1 = new ArrayList<String>();
ArrayList<String> arrButton2 = new ArrayList<String>();
ArrayList<String> arrToChoose;
if(s.equals("button1")) { 
  arrToChoose = arrButton1;
} else if(s.equals("button2")) {
  arrToChoose = arrButton2;
}
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, arrayToChoose));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜