使用自定义Layout代替ViewHolder

个人主页为 The_D的博客

很多人使用 Listview 时,总是用 ViewHolder 的模式来创建,而根据 Customizing Android ListView Rows by Subclassing 中说的,ViewHolder 是一种愚笨的方式。在这篇文章中,作者提出了一个新的思路,也就是通过自定义的 Layout 来代替 ViewHolder。

ViewHolder的缺点

  • Adapter 的 getView() 函数承担了很多责任
  • ViewHolder 类中通常是一些无意义的代码
  • view 的 tag 需要转换到正确的 holder 类型
  • 违反了封装性,因为 adapter/holder 必须知道 item 内部有什么 view

demo:

动图
动图

下面来说说如何实现:

首先,创建item_relative_layout.xml:
item由头像ImageView,名字TextView和描述TextView构成

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="200dp">

    <ImageView
        android:id="@+id/iv"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:scaleType="fitCenter"
        android:layout_centerVertical="true"
        android:layout_marginLeft="10dp"
        />

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/iv"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="60dp"
        android:textSize="16sp"
        />

    <TextView
        android:id="@+id/description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/iv"
        android:layout_below="@id/tv_title"
        android:layout_marginTop="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:textSize="14sp"
        />

</RelativeLayout>

然后,创建CustomRelativeLayout.java:

public class CustomRelativeLayout extends RelativeLayout {

    //使用ButterKnife注解的方式,简化了findViewById
    @Bind(R.id.iv)
    ImageView mIv;
    @Bind(R.id.tv_title)
    TextView mTvTitle;
    @Bind(R.id.description)
    TextView mDescription;

    public CustomRelativeLayout(Context context) {
        super(context);
        init(context);
    }

    private void init(Context context) {
        LayoutInflater.from(context).inflate(R.layout.item_relative_layout, this);
        ButterKnife.bind(this);
        //因为每一个item的listener都相同,所以将clickListener写在这个类中,如果不同,可写在adapter的getView()中根据position设置不同listener
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(), mTvTitle.getText().toString() + " " + mDescription.getText().toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void setData(int iv, String title, String description){
        mIv.setImageResource(iv);
        mTvTitle.setText(title);
        mDescription.setText(description);
    }
}

ListAdapter.java:

public class ListAdapter extends BaseAdapter {

    Context mContext;
    int[] images;
    String[] titles;
    String[] descriptions;

    public ListAdapter(Context context) {
        mContext = context;
    }

    public void setData(int[] images, String[] titles, String[] descriptions) {
        this.images = images;
        this.titles = titles;
        this.descriptions = descriptions;
    }

    @Override
    public int getCount() {
        return images.length;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
    
    //相对于ViewHolder简化了getView
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        CustomRelativeLayout customRelativeLayout = null;
        if (convertView != null && convertView instanceof CustomRelativeLayout) {
            customRelativeLayout = (CustomRelativeLayout) convertView;
        } else {
            customRelativeLayout = new CustomRelativeLayout(mContext);
        }
        customRelativeLayout.setData(images[position], titles[position], descriptions[position]);
        return customRelativeLayout;
    }
}

UsingCustomLayoutActivity.java:

public class UsingCustomLayoutActivity extends AppCompatActivity {

    @Bind(R.id.lv)
    ListView mLv;
    ListAdapter mListAdapter;
    int[] images = {R.drawable.p1, R.drawable.p2, R.drawable.p3};
    String[] titles = {"The_D", "闫一彪", "Android技术小铺"};
    String[] descriptions = {"Android开发", "Java后端开发", "我的微信公众号,专注于Android技术分享,欢迎关注"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_using_custom_layout);
        ButterKnife.bind(this);
        mListAdapter = new ListAdapter(this);
        mListAdapter.setData(images, titles, descriptions);
        mLv.setAdapter(mListAdapter);
    }
}

activity_using_custom_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.zhangkaiyue.jkdemo.UsingCustomLayoutActivity">

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</RelativeLayout>

这种做法的优势:

这样写可以使item复用,并且针对复杂的Adapter,大大的简化了书写。对于一些跟View相关的逻辑,可以直接写在CustomRelativeLayout中,消除了Adapter的冗余。


我的微信公众号
我的微信公众号
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,509评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,806评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,875评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,441评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,488评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,365评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,190评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,062评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,500评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,706评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,834评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,559评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,167评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,779评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,912评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,958评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,779评论 2 354

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,112评论 25 707
  • 一、适用场景 ListViewListview是一个很重要的组件,它以列表的形式根据数据的长自适应展示具体内容,用...
    Geeks_Liu阅读 10,668评论 1 28
  • 借一盏残灯深夜里清醒 望半杯清茶孤独里暖心
    慕晨的记事本阅读 181评论 0 0
  • 最近看《教父》这本书,本来听说这是什么男人励志必读,可是哪有看一本书就能够励志的呢,还有《肖申克的救赎》。也许也是...
    永恒恒阅读 263评论 0 1
  • 我是一颗种子 在黑暗里 努力伸展向下,向下,再向下 吸取大地之精华 我无声的伸展向上,向上,再向上 寻找那生命之光...
    绿洲玫瑰阅读 260评论 0 1