2011-04-06 38 views

回答

0

list_layout.xml

<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/list" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" /> 

</LinearLayout> 

row_layout.xml

<?xml version="1.0" encoding="utf-8"?> 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 

    <TextView android:id="@+id/row_text" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" /> 

    <ImageView android:id="@+id/row_image" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" /> 

</LinearLayout> 

在的onCreate()

setContentView(R.layout.list_layout); 
ListView lv = (ListView) findViewById(R.id.list); 
List<ListRow> list = new ArrayList<ListRow>(); 

for (loop through your data) { 
    list.add(new ListRow("text", R.drawable.image)); 
} 

YourAdapter adapter = new YourAdapter(this, list); 
lv.setAdapter(adapter); 

的類

class ListRow { 
    private String text; 
    private int resource; 

    public ListRow(String text, int resource) { 
     super(); 
     this.text = text; 
     this.resource = resource; 
    } 

    public int getText() { 
     return text; 
    } 
    public int getResource() { 
     return resource; 
    } 
} 

class YourAdapter extends BaseAdapter implements OnClickListener { 
    private Context context; 

    private List<ListRow> theList; 

    public YourAdapter (Context context, List<ListRow> theList) { 
     this.context = context; 
     this.theList = theList; 
    } 

    public View getView(int position, View convertView, ViewGroup viewGroup) { 
     ListRow row = theList.get(position); 

     if (convertView == null) { 
      LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      convertView = inflater.inflate(R.layout.row_layout, null); 
     } 

     TextView tv = (TextView) convertView.findViewById(R.id.row_text); 
     tv.setText(row.getText()); 

     ImageView iv = (ImageView) convertView.findViewById(R.id.row_image); 
     iv.setBackgroundResource(row.getResource()); 

     return convertView; 
    } 

    @Override 
    public void onClick(DialogInterface dialog, int which) { 

    } 
} 
相關問題