问题
I'm having a problem here, I'm totally new at this.
What i try to do is pass a JSONObject to my adapter and inside my adapter create all rows for that ListView
This is my code:
private static final String TAG_OS = "android";
protected void onPostExecute(JSONObject json) {
try {
JSONArray jArray = json.getJSONArray(TAG_OS);
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
menu_list=(ListView)findViewById(R.id.menu_list);
MenuAdapter adapter = new MenuAdapter(MainActivity.this, new ArrayList[] {listdata} );
menu_list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
My adapter is this one:
public class MenuAdapter extends ArrayAdapter<ArrayList> {
private final Context context;
private final ArrayList[] values;
public MenuAdapter(Context context,ArrayList[] values) {
super(context, R.layout.menu_main, values);
this.context = context;
this.values = values;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.menu_main, parent, false);
if (position % 2 == 1) {
rowView.setBackgroundColor(Color.RED);
} else {
rowView.setBackgroundColor(Color.BLUE);
}
return rowView;
}
I still have no idea how to populate the whole ListView, Its just one TextView with alternate backgrounds. What i don't understand yet is how to set one row after another, haven't found a good example.
How can I resolve this? :s
回答1:
As you are using just a single text field in your code you need not make a custom Adapter just for that as you can use Android's ArrayAdapter
.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, listdata.toArray());
menu_list.setAdapter(adapter);
This snippet uses default Android List layout and a TextView which will take care of adding multiple rows for you.
Edit: It looks like you need to use to use BaseAdapter for that you would need to make a class that extends BaseAdapter and use a ViewHolder, look at this blog which I wrote androidadapternotifiydatasetchanged.blogspot.in, it has a class which extends BaseAdapter and it uses a custom layout (.xml) file, you will get a basic idea of how its done
来源:https://stackoverflow.com/questions/23304684/android-jsonobject-to-listview