初级ListView万能适配器



import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

/**
 * Author:Will on 2016/11/23 14:38
 * Mail:heheheqin.will@gmail.com
 * <p>
 * 自定义抽象万能 BaseAdapter
 */
package com.dream.will.absasapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

/**
 * Author:Will on 2016/12/8 12:37
 * Mail:heheheqin.will@gmail.com
 */

public abstract class AbsBaseAdapter2<T> extends BaseAdapter {
    //数据源
    List<T> data;
    LayoutInflater inflater;
    //布局
    int[] layoutId;
    //构造方法


    public AbsBaseAdapter2(Context context, List<T> data, int... layoutId) {
        this.data = data;
        this.inflater = LayoutInflater.from(context);
        this.layoutId = layoutId;
    }

    // TODO: 2016/11/23
    @Override
    public int getViewTypeCount() {
        return layoutId.length;
    }

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

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

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


    // 当前布局布局的类型
    @Override
    public abstract int getItemViewType(int position);

    //抽吸那个绑定数据方法
    public abstract  void  bindData(int position,ViewHolder viewHolder);

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolde;
        int itemViewType = getItemViewType(position);
        if (convertView == null) {
            convertView = inflater.inflate(layoutId[itemViewType], parent, false);
            viewHolde = new ViewHolder(convertView);
            convertView.setTag(viewHolde);
        } else {
            viewHolde = (ViewHolder) convertView.getTag();
        }
        bindData(position,viewHolde);
        return convertView;
    }


   
public static class ViewHolder{
    //保存的控件 是需要设置值的控件
    private View view;
    //通过SparsArray找到缓存布局  特点:二分查找  键只能是integer类型  占用内存小
    private SparseArray<View> mViews;
    public ViewHolder(View c){
        this.view = c;
        this.mViews = new SparseArray<View>();
    }

    //向子类提供一个方法,返回需要设置值的控件
    public  View findViewBid(int viewId){
        //根据viewID找到对应控件
        View findView = mViews.get(viewId);
        if (findView == null){
            findView = view.findViewById(viewId);
            mViews.put(viewId,findView);
        }
        return findView;
    }
}


}






例子

public class MainActivity extends AppCompatActivity {

    String url = "http://ikft.house.qq.com/index.php?guid=866500021200250&devua=appkft_1080_1920_XiaomiMI4LTE_1.8.3_Android19&devid=866500021200250&appname=QQHouse&mod=appkft&reqnum=20&pageflag=0&act=newslist&channel=71&buttonmore=1&cityid=1";
    List<Bean> data;
    private ListView listview;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.i("TAG", "handleMessage: ---------" );
            AbsBaseAdapter2<Bean> adapter = new AbsBaseAdapter2<Bean>(MainActivity.this,
                    data,
                    R.layout.item1,
                    R.layout.item2) {
                @Override
                public int getItemViewType(int position) {
                    return Integer.parseInt(data.get(position).getType());
                }

                @Override
                public void bindData(int position, ViewHolder viewHolder) {
                    Bean bean = data.get(position);
                    Log.i("TAG", "bindData: ---------" +bean.toString() );
                    if ("0".equals(bean.getType())) {
                        ImageView image = (ImageView) viewHolder.findViewBid(R.id.item1_img);
                        TextView text = (TextView) viewHolder.findViewBid(R.id.item1_text);
                        text.setText(bean.getTitle());
                        Glide.with(MainActivity.this).load(bean.getThumbnail()).into(image);
                    } else if("1".equals(bean.getType())){
                        ImageView image = (ImageView) viewHolder.findViewBid(R.id.item2_img);
                        TextView text = (TextView) viewHolder.findViewBid(R.id.item2_text);
                        Log.i("TAG", "bindData: ---------" +bean.getTitle() );
                        text.setText(bean.getTitle());
                        Glide.with(MainActivity.this).load(bean.getThumbnail()).into(image);
                    }
                }
            };

            listview.setAdapter(adapter);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        data = new ArrayList<>();
        getData();
    }

    private void initView() {
        listview = (ListView) findViewById(R.id.listview);
    }

    public void getData() {
        OkHttpClient cl = new OkHttpClient.Builder().build();
        Request re = new Request.Builder()
                .url(url)
                .build();
        cl.newCall(re).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                Log.i("TAG", "onResponse: json---------" + json);
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    String data1 = jsonObject.getString("data");
                    JSONArray jsonArray = new JSONArray(data1);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonBean = jsonArray.getJSONObject(i);
                        data.add(new Bean(jsonBean));
                    }
                    Log.i("TAG", "onResponse: data.size()---------" + data.size());
                    handler.sendEmptyMessage(0);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }
}


package com.dream.will.absasapter;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Author:Will on 2016/12/8 12:38
 * Mail:heheheqin.will@gmail.com
 */

public class Bean {

    private String id;
    private String type;
    private String title;
    private String summary;
    private String thumbnail;
    private String groupthumbnail;
    private int commentcount;
    private int imagecount;
    private String commentid;

    public Bean(JSONObject j) throws JSONException {
        id = j.optString("id");
        type = j.optString("type");
        title = j.optString("title");
        thumbnail = j.optString("thumbnail");
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public String getThumbnail() {
        return thumbnail;
    }

    public void setThumbnail(String thumbnail) {
        this.thumbnail = thumbnail;
    }

    public String getGroupthumbnail() {
        return groupthumbnail;
    }

    public void setGroupthumbnail(String groupthumbnail) {
        this.groupthumbnail = groupthumbnail;
    }

    public int getCommentcount() {
        return commentcount;
    }

    public void setCommentcount(int commentcount) {
        this.commentcount = commentcount;
    }

    public int getImagecount() {
        return imagecount;
    }

    public void setImagecount(int imagecount) {
        this.imagecount = imagecount;
    }

    public String getCommentid() {
        return commentid;
    }

    public void setCommentid(String commentid) {
        this.commentid = commentid;
    }

    @Override
    public String toString() {
        return "Bean{" +
                "id='" + id + '\'' +
                ", type='" + type + '\'' +
                ", title='" + title + '\'' +
                ", summary='" + summary + '\'' +
                ", thumbnail='" + thumbnail + '\'' +
                ", groupthumbnail='" + groupthumbnail + '\'' +
                ", commentcount=" + commentcount +
                ", imagecount=" + imagecount +
                ", commentid='" + commentid + '\'' +
                '}';
    }
}

mian布局
<?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:id="@+id/activity_main"
    android:layout_width="match_parent" android:layout_height="match_parent"
    tools:context="com.dream.will.absasapter.MainActivity">

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

item1布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/item1_img"
        android:src="@mipmap/ic_launcher"
        android:layout_width="40dp"
        android:layout_height="40dp" />
    <TextView
        android:id="@+id/item1_text"
        android:text="hehehhe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>
itme2 布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/item2_img"
        android:src="@mipmap/ic_launcher"
        android:layout_width="40dp"
        android:layout_height="40dp" />

    <TextView
        android:id="@+id/item2_text"
        android:text="heheheh"
        android:textColor="@color/colorAccent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值