Android 自定义 ListView (2)

基于前文,将 Adapter 单独出来。

MyBaseAdapter.java

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

class MyBaseAdapter extends BaseAdapter {

    public String[] names;
    public int[] icons;

    private Context mContext;

    public MyBaseAdapter(Context context) {
        super();
        this.mContext = context;
    }
    
    //得到 Item 的总数
    public int getCount() {
        //返回ListView Item 条目的总数
        return names.length;
    }
    
    //得到 Item 代表的对象
    public Object getItem(int position) {
        //返回ListView Item 条目代表的对象
        return names[position];
    }
    
    //得到 Item 的 id
    public long getItemId(int position) {
        //返回 ListView Item 的 id
        return position;
    }
    
    //得到 Item 的 View 视图
    public View getView(int position, View convertView, ViewGroup parent) {
        //将 list_item.xml 文件找出来并转换成 View 对象
        View view = View.inflate(this.mContext,R.layout.list_item, null);

        TextView textView = view.findViewById(R.id.tv_list);
        textView.setText(names[position]);

        ImageView imageView = view.findViewById(R.id.image);
        imageView.setBackgroundResource(icons[position]);

        return view;
    }
}

则 MainActivity.java:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

    private ListView listView;

    private String[] names = new String[] {"滴滴","钉钉","爱奇艺","假多多","酷狗","美团","陌陌","QQ","淘宝","微信","支付宝"};
    private int[] icons = {
            R.mipmap.app_didi,
            R.mipmap.app_dingding,
            R.mipmap.app_iqiyi,
            R.mipmap.app_jiaduoduo,
            R.mipmap.app_kugou,
            R.mipmap.app_meituan,
            R.mipmap.app_momo,
            R.mipmap.app_qq,
            R.mipmap.app_taobao,
            R.mipmap.app_wechat,
            R.mipmap.app_zhifubao
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = findViewById(R.id.lv);

        MyBaseAdapter adapter = new MyBaseAdapter(this);
        adapter.icons = icons;
        adapter.names = names;

        listView.setAdapter(adapter);
    }
}