Boomark
不需要扩展ArrayList
。您需要做的是为您的书签对象创建一个自定义适配器并在您的 ListView 上使用该适配器。
首先创建您的书签模型类。
public class Bookmark {
private String title;
private String url;
private Drawable icon;
public Bookmark(String title, String url, Drawable icon) {
this.title = title;
this.url = url;
this.icon = icon;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Drawable getIcon() {
return icon;
}
public void setIcon(Drawable icon) {
this.icon = icon;
}
}
然后创建您的书签适配器
public class BookmarkAdapter extends BaseAdapter{
private ArrayList<Bookmark> bookmarks;
private Context context;
public BookmarkAdapter(Context context, ArrayList<Bookmark> bookmarks) {
this.context = context;
this.bookmarks = bookmarks;
}
public int getCount() {
return bookmarks.size();
}
public Object getItem(int position) {
return bookmarks.get(position);
}
public long getItemId(int arg0) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if ( row == null ) {
row = View.inflate( context, R.layout.row_bookmark, null );
}
Bookmark bookmark = (Bookmark)getItem(position);
if ( bookmark!= null ) {
TextView name = (TextView) row.findViewById( R.id.title );
if ( name != null ) {
name.setText( bookmark.getTitle() );
}
}
return row;
}
}
这row_bookmark.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
把它放在你的Activity
xml中
<ListView
android:id="@+id/bookmark_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
在您的活动中填充列表
String[] titles = getResources().getStringArray(R.array.bookmark_titles);
String[] urls = getResources().getStringArray(R.array.bookmark_urls);
TypedArray icons = getResources().obtainTypedArray(R.array.bookmark_icons);
ArrayList<Bookmark> bookmarks = new ArrayList<Bookmark>();
for (int i = 0; i < titles.length; i ++) {
bookmarks.add(new Bookmark(titles[i], urls[i], icons.getDrawable(i)));
}
ListView bookmarkList = (ListView)findViewById(R.id.bookmark_list);
bookmarkList.setAdapter(new BookmarkAdapter(this, bookmarks));
要在选择列表项时获取 URL,您需要设置项目单击侦听器
bookmarkList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String url = ((Bookmark)parent.getAdapter().getItem(position)).getUrl();
}
});