2011-07-09 25 views
1

我想扩展我简单的ListActivity,使每个项目旁边都有小图片。这是我到目前为止的代码:Android - 扩展ListActivity为每个项目添加图像?

的main.xml:

<?xml version="1.0" encoding="utf-8"?> 
<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@android:id/text1" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:textAppearance="?android:attr/textAppearanceLarge" 
android:gravity="center_vertical" 
android:paddingLeft="6dip" 
android:minHeight="?android:attr/listPreferredItemHeight" /> 

MainActivity.java:

public class MainActivity extends ListActivity { 


/** Called when the activity is first created. */ 
public void onCreate(Bundle icicle) { 
    super.onCreate(icicle); 
    // Create an array of Strings, that will be put to our ListActivity 
    String[] names = new String[] { "some", "list", "items", "which", "each", "have", "their", "own", "image"}; 


    this.setListAdapter(new ArrayAdapter<String>(this,R.layout.main, names)); 


} 

@Override 
protected void onListItemClick(ListView l, View v, int position, long id) { 
    super.onListItemClick(l, v, position, id); 
    // Get the item that was clicked 
    Object o = this.getListAdapter().getItem(position); 
    String keyword = o.toString(); 
    Toast.makeText(this, "You selected: " + keyword, Toast.LENGTH_SHORT) 
      .show(); 
} 

}

而且我得到了像10项(串)和他们每个人都有一张我想放在旁边的图像,例如itemImage1.png,itemImage2.png,...等。

我该怎么做?

感谢您的任何帮助。

回答

2

我做了一段时间后回来。使用的LazyLoader这里找到lazyloader

看起来是关键代码,重写getView方法

public static class ViewHolder{ 

     public TextView text; 

     public ImageView image; 

    } 



    public View getView(int position, View convertView, ViewGroup parent) { 

     View vi=convertView; 

     ViewHolder holder; 

     if(convertView==null){ 

      vi = inflater.inflate(R.layout.item, null); 

      holder=new ViewHolder(); 

      holder.text=(TextView)vi.findViewById(R.id.text);; 

      holder.image=(ImageView)vi.findViewById(R.id.image); 

      vi.setTag(holder); 

     } 

     else 

      holder=(ViewHolder)vi.getTag(); 



     holder.text.setText("item "+position); 

     holder.image.setTag(data[position]); 

     imageLoader.DisplayImage(data[position], activity, holder.image); 

     return vi; 

    } 
+0

嘿感谢,我只是有种不确定如何实现这一点。什么是item.xml文件?什么是数据对象?这行是什么:imageLoader.DisplayImage(data [position],activity,holder.image); ?虽然 – JDS

+0

看起来像数据是一个URL []的URL。 imageLoader.DisplayImage将采用第一个参数(URL),下载图像并将其加载到第三个参数(您的列表项)中。 xml需要包含一个textview和一个imageview。把它想象成代表你的列表中的一行。 您必须将活动和URL的字符串[]传递到列表活动中。如果你想传递一个字符串[],它会很容易修改。我只需下载代码并在其中进行浏览;如果有的话,你应该很容易实现,而不用理解太多的细节。 – marklar

相关问题