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>
填充列表我n您的活動
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();
}
});
謝謝你的偉大的答案。我已經有了Bookmark類。還有一個問題。我已經有了getBookmark()方法,它已經完成了在我的活動中填充列表的動作。我怎樣才能在我的主類中調用這個方法? – androidstudent
您可以使用'bookmarkList.setAdapter(new BookmarkAdapter(this,Bookmark.getBookmark(this));' –
再次感謝您。 – androidstudent