- 创建延伸BaseAdpter或ArrayAdpter定制适配器并通过阵列或ArrayList的在构造
- 在
- (列)的布局创建视图充气此xml在定制适配器的getView功能,并设置数据
如
http://www.josecgomez.com/2010/05/03/android-putting-custom-objects-in-listview/
Populate Listview from JSON
你跟我混既能让你明白......
活动XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/lstText"
/>
</LinearLayout>
列表行XML(布局row.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">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/txtAlertText" />
</LinearLayout>
</LinearLayout>
您适配器类
class JSONAdapter extends BaseAdapter implements ListAdapter {
private final Activity activity;
private final JSONArray jsonArray;
private JSONAdapter (Activity activity, JSONArray jsonArray) {
assert activity != null;
assert jsonArray != null;
this.jsonArray = jsonArray;
this.activity = activity;
}
@Override public int getCount() {
if(null==jsonArray)
return 0;
else
return jsonArray.length();
}
@Override public JSONObject getItem(int position) {
if(null==jsonArray) return null;
else
return jsonArray.optJSONObject(position);
}
@Override public long getItemId(int position) {
JSONObject jsonObject = getItem(position);
return jsonObject.optLong("id");
}
@Override public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = activity.getLayoutInflater().inflate(R.layout.row, null);
TextView text =(TextView)convertView.findViewById(R.id.txtAlertText);
JSONObject json_data = getItem(position);
if(null!=json_data){
String jj=json_data.getString("f_name");
text.setText(jj);
}
return convertView;
}
}
您activty
public class main extends Activity {
/** Called when the activity is first created. */
ListView lstTest;
//Array Adapter that will hold our ArrayList and display the items on the ListView
JSONAdapter jSONAdapter ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Initialize ListView
lstTest= (ListView)findViewById(R.id.lstText);
jSONAdapter = new JSONAdapter (main.this,jArray);//jArray is your json array
//Set the above adapter as the adapter of choice for our list
lstTest.setAdapter(jSONAdapter);
}
我不明白这不你甲肝一个简单的例子? –
我觉得第二个很简单......不是......? –
但它给出了错误,你可以编辑我的代码,因为我希望在这个问题上? –