Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android ListView 新聞案例:BaseAdapter 與 convertView 復用完整教學

編輯:關於 Android 開發

Android ListView 新聞案例:BaseAdapter 與 convertView 復用完整教學


這個案例用 ListView 做一個新聞列表:每個條目包含圖示、標題與描述,點擊後用瀏覽器打開對應新聞網址。這是理解客製化 ListView 最經典的練習。

先看主布局,只放一個 ListView:

<?xml version="1.0"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/lv_news"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</RelativeLayout>

資料模型 NewsBean:

package com.itheima.news_listview.bean;

import android.graphics.drawable.Drawable;

public class NewsBean {
    public String title;
    public String des;
    public Drawable icon;
    public String news_url;
}

假資料來源 NewsUtils,這裡用迴圈產生 100 組資料模擬後端:

package com.itheima.news_listview.utils;

import java.util.ArrayList;
import android.content.Context;
import com.itheima.news_listview.R;
import com.itheima.news_listview.bean.NewsBean;

public class NewsUtils {
    public static ArrayList<NewsBean> getAllNews(Context context) {
        ArrayList<NewsBean> arrayList = new ArrayList<NewsBean>();
        for (int i = 0; i < 100; i++) {
            NewsBean newsBean = new NewsBean();
            newsBean.title = "謝霆鋒經紀人:偷拍系侵權行為";
            newsBean.des = "稱謝霆鋒隱私權受到侵犯,將保留追究法律責任";
            newsBean.news_url = "https://www.sina.cn";
            // 通過 context 將資源 id 轉換成 Drawable 物件
            newsBean.icon = context.getResources().getDrawable(R.drawable.ic_launcher);
            arrayList.add(newsBean);

            NewsBean newsBean1 = new NewsBean();
            newsBean1.title = "知情人:王菲是謝霆鋒心頭最愛的人";
            newsBean1.des = "身邊的人都知道謝霆鋒最愛王菲,二人早有復合跡象";
            newsBean1.news_url = "https://www.baidu.cn";
            newsBean1.icon = context.getResources().getDrawable(R.drawable.icon);
            arrayList.add(newsBean1);

            NewsBean newsBean2 = new NewsBean();
            newsBean2.title = "熱烈祝賀黑馬74高薪就業";
            newsBean2.des = "74期平均薪資20000,其中有一位同學超過10萬";
            newsBean2.news_url = "https://www.itheima.com";
            newsBean2.icon = context.getResources().getDrawable(R.drawable.icon2);
            arrayList.add(newsBean2);
        }
        return arrayList;
    }
}

核心的 NewsAdapter,繼承 BaseAdapter 並覆寫四個方法。getView 裡的 convertView 復用是效能關鍵:

package com.itheima.news_listview.adapter;

import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.itheima.news_listview.R;
import com.itheima.news_listview.bean.NewsBean;

public class NewsAdapter extends BaseAdapter {
    private ArrayList<NewsBean> list;
    private Context context;

    // 通過構造方法接受要顯示的新聞數據集合
    public NewsAdapter(Context context, ArrayList<NewsBean> list) {
        this.list = list;
        this.context = context;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;
        // 1. 復用 convertView 優化 listview
        if (convertView != null) {
            view = convertView;
        } else {
            // 常見的三種 inflate 寫法:
            // view = View.inflate(context, R.layout.item_news_layout, null);
            // view = LayoutInflater.from(context).inflate(R.layout.item_news_layout, null);
            LayoutInflater layoutInflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = layoutInflater.inflate(R.layout.item_news_layout, null);
        }
        // 2. 獲取 view 上的子控件
        ImageView item_img_icon = (ImageView) view.findViewById(R.id.item_img_icon);
        TextView item_tv_des = (TextView) view.findViewById(R.id.item_tv_des);
        TextView item_tv_title = (TextView) view.findViewById(R.id.item_tv_title);
        // 3. 獲取 position 位置對應的資料
        NewsBean newsBean = list.get(position);
        // 4. 將資料設置給子控件
        item_img_icon.setImageDrawable(newsBean.icon);
        item_tv_title.setText(newsBean.title);
        item_tv_des.setText(newsBean.des);
        return view;
    }
}

最後在 Activity 裡把 Adapter 設給 ListView,並設定條目點擊事件做跳轉:

// 設置 listview 條目的點擊事件
lv_news.setOnItemClickListener(this);

// parent: listview  view: 點擊的條目  position: 條目位置  id: 條目 id
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    // 取得條目上的 bean 物件,取出 url
    NewsBean bean = (NewsBean) parent.getItemAtPosition(position);
    String url = bean.news_url;
    // 跳轉瀏覽器
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setData(Uri.parse(url));
    startActivity(intent);
}

整個流程可以濃縮成七步:

1. 布局裡寫 ListView;2. 找到 ListView;3. 把資料封裝進 List 集合作為 Adapter 的資料源;4. 自訂 Adapter 繼承 BaseAdapter 並覆寫 getCount、getView、getItem、getItemId;5. 建立 Adapter 物件並 setAdapter;6. 設定條目點擊事件;7. 在 onItemClick 中取出 bean 的 url 做 Intent 跳轉。

其中 getView 的四個要點:先復用 convertView(若為 null 才 inflate 布局),再 findViewById 取得子控件,接著從 list 取出 position 對應的 bean,最後把資料填進子控件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved