欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

万能适配器多布局上拉下拉刷新

程序员文章站 2022-05-04 19:25:15
万能适配器导入依赖//万能适配器implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.22'//SmartRefreshLayoutimplementation 'com.scwang.smartrefresh:SmartRefreshLayout:1.1.0' 主布局

万能适配器

导入依赖

//万能适配器
implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.22'
//SmartRefreshLayout
implementation 'com.scwang.smartrefresh:SmartRefreshLayout:1.1.0' 

主布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <com.scwang.smartrefresh.layout.SmartRefreshLayout
        android:id="@+id/smart_id"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyler_id"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </androidx.recyclerview.widget.RecyclerView>
    </com.scwang.smartrefresh.layout.SmartRefreshLayout>


</LinearLayout>

OkHttpUtils工具类

public class OkHttpUtils {
    private OkHttpClient okHttpClient;
    private Handler handler = new Handler();

    private OkHttpUtils() {
        okHttpClient = new OkHttpClient.Builder()
                .writeTimeout(60 * 1000, TimeUnit.MILLISECONDS)
                .readTimeout(60 * 1000, TimeUnit.MILLISECONDS)
                .build();
    }

    private static OkHttpUtils okHttpUtils = new OkHttpUtils();

    public static OkHttpUtils getInstance() {
        return okHttpUtils;
    }

    //get请求
    public void doget(String url, final OkhttpCallBack okhttpCallBack) {
        Request request = new Request.Builder().get().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                final String message = e.getMessage();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        okhttpCallBack.onError(message);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String string = response.body().string();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        okhttpCallBack.onOk(string);
                    }
                });
            }
        });
    }

    //post请求
    public void dopost(String url, HashMap<String, String> map, final OkhttpCallBack okhttpCallBack) {
        Set<Map.Entry<String, String>> entries = map.entrySet();
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : entries) {
            builder.add(entry.getKey(), entry.getValue());
        }
        FormBody formBody = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                final String message = e.getMessage();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        okhttpCallBack.onError(message);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String string = response.body().string();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        okhttpCallBack.onOk(string);
                    }
                });
            }
        });
    }

}

OkHttpCallBack

public interface OkhttpCallBack {
    void onError(String message);

    void onOk(String json);
}

万能适配器

public class MyAdapter extends BaseQuickAdapter<FoodBean.DataBean, BaseViewHolder> {

    public MyAdapter(int layoutResId, @Nullable List<FoodBean.DataBean> data) {
        super(layoutResId, data);
    }

    @Override
    protected void convert(BaseViewHolder helper, FoodBean.DataBean item) {
        helper.setText(R.id.text_item, item.getTitle() + "");
        ImageView img = helper.getView(R.id.img_item);
        Glide.with(mContext).load(item.getPic()).into(img);
        helper.addOnClickListener(R.id.img_item)
                .addOnClickListener(R.id.text_item);
    }
}

Activity

public class MainActivity extends AppCompatActivity {
    private RecyclerView recylerId;
    private SmartRefreshLayout smartId;
    private List<FoodBean.DataBean> dataBeans = new ArrayList<>();
    private MyAdapter myAdapter;
    private int page = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recylerId = (RecyclerView) findViewById(R.id.recyler_id);
        smartId = (SmartRefreshLayout) findViewById(R.id.smart_id);
        
        myAdapter = new MyAdapter(R.layout.layout_item, dataBeans);
        recylerId.setAdapter(myAdapter);
        recylerId.setLayoutManager(new LinearLayoutManager(this));
        recylerId.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        
        //点击事件
        myAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Toast.makeText(MainActivity.this, "点击了" + position, Toast.LENGTH_SHORT).show();
            }
        });
        
        //点击事件
        myAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.img_item:
                        Toast.makeText(MainActivity.this, "点击了图片" + position, Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.text_item:
                        Toast.makeText(MainActivity.this, "点击了文字" + position, Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });

        //添加头布局和尾布局
        View head = LayoutInflater.from(this).inflate(R.layout.head, null);
        View foot = LayoutInflater.from(this).inflate(R.layout.foot, null);
        myAdapter.addHeaderView(head);
        myAdapter.addFooterView(foot);

        //添加动画
        //默认渐显
//        myAdapter.openLoadAnimation();
        //缩放
//        myAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        //从右到左
        myAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_RIGHT);
        //从左到右
//        myAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT);
        //从下到上
//        myAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);


        //横滑删除   上下拖拽
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            //支持设置方向
            @Override
            public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                return makeMovementFlags(ItemTouchHelper.UP | ItemTouchHelper.DOWN, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT);
            }

            //上下拖拽
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                int adapterPosition = viewHolder.getAdapterPosition();
                int adapterPosition1 = target.getAdapterPosition();
                Collections.swap(dataBeans, adapterPosition, adapterPosition1);
                myAdapter.notifyDataSetChanged();
                return true;
            }

            //左右滑动
            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                int position = viewHolder.getAdapterPosition();
                dataBeans.remove(position);
                myAdapter.notifyDataSetChanged();
            }
        });
        itemTouchHelper.attachToRecyclerView(recylerId);

        //上拉下拉
        smartId.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                //加载完成
                smartId.finishLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                dataBeans.clear();
                page = 1;
                //通知刷新完成
                smartId.finishRefresh();
            }
        });
        
        
        OkHttpUtils.getInstance().doget("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=" + page, new OkhttpCallBack() {
            @Override
            public void onError(String message) {

            }

            @Override
            public void onOk(String json) {
                Toast.makeText(MainActivity.this, "" + json, Toast.LENGTH_SHORT).show();
                FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
                List<FoodBean.DataBean> data = foodBean.getData();
                dataBeans.addAll(data);
                myAdapter.notifyDataSetChanged();

            }
        });
    }
}

item布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/img_item"
        android:layout_width="100dp"
        android:layout_height="100dp" />

    <TextView
        android:id="@+id/text_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

头布局和尾布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:orientation="vertical">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@mipmap/ic_launcher" />
</LinearLayout>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="电话:11111111111" />
</LinearLayout>

多布局

布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyler_id"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </androidx.recyclerview.widget.RecyclerView>

</LinearLayout>

Bean类

public class JavaBean implements MultiItemEntity {
    private String text;
    private String image;
    private int type;

    public JavaBean(String text, String image, int type) {
        this.text = text;
        this.image = image;
        this.type = type;
    }

    //尤为重要
    @Override
    public int getItemType() {
        return type;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public int getType() {
        return type;
    }

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

适配器

public class MyAdapter extends BaseMultiItemQuickAdapter<JavaBean, BaseViewHolder> {

    public MyAdapter(List<JavaBean> data) {
        super(data);
        addItemType(0, R.layout.layout_text);
        addItemType(1, R.layout.layout_image);
        addItemType(2,R.layout.layout_item);
    }

    @Override
    protected void convert(BaseViewHolder helper, JavaBean item) {
        switch (helper.getItemViewType()) {
            case 0:
                helper.setText(R.id.text_id, item.getText() + "");
                break;
            case 1:
                ImageView img = helper.getView(R.id.img_id);
                Glide.with(mContext).load(item.getImage()).into(img);
                break;
            case 2:
                helper.setText(R.id.text_id, item.getText() + "");
                ImageView imgs = helper.getView(R.id.img_id);
                Glide.with(mContext).load(item.getImage()).into(imgs);
                break;
        }
    }
}

Activity代码

public class MainActivity extends AppCompatActivity {
    private RecyclerView recylerId;
    private MyAdapter myAdapter;
    private List<JavaBean> javaBeanList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recylerId = (RecyclerView) findViewById(R.id.recyler_id);
        myAdapter = new MyAdapter(javaBeanList);
        recylerId.setAdapter(myAdapter);
        recylerId.setLayoutManager(new LinearLayoutManager(this));
        recylerId.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        javaBeanList.add(new JavaBean("啊哈", "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1595323372&di=52fbb5251d0c852f3697c2b37fdf9dcb&src=http://img.pcauto.com.cn/images/upload/upc/tx/qn/bbs6/1812/16/c15/123982074_1544933813493_700x700.jpg", 0));
        javaBeanList.add(new JavaBean("啊哈", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1595333516043&di=3216a28011c4647be105a612932e6d0b&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Fb8fba79aee2fff96bbfca5460a509c756b9ecb7f1bdaa-R1H09T_fw236", 1));
        javaBeanList.add(new JavaBean("龙儿龙儿,我是过儿", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1595333516043&di=dbc104246b89d9e73cf87d8a83583e4c&imgtype=0&src=http%3A%2F%2Fwww.smyyqd.com%2Fimg%2Fuvbha3fh33r.jpg", 2));
        javaBeanList.add(new JavaBean("啊哈", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1595333516042&di=79dec01a07ab76feac8e8282561877c6&imgtype=0&src=http%3A%2F%2Fimg.pcauto.com.cn%2Fimages%2Fupload%2Fupc%2Ftx%2Fbbs6%2F1609%2F22%2Fc68%2F27348615_1474520368278_1024x1024.jpg", 2));
        myAdapter.notifyDataSetChanged();
    }
}

子布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="10dp">

    <ImageView
        android:id="@+id/img_id"
        android:layout_width="100dp"
        android:layout_height="100dp" />

    <TextView
        android:id="@+id/text_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="10dp">

    <ImageView
        android:id="@+id/img_id"
        android:layout_width="match_parent"
        android:layout_height="100dp" />
</LinearLayout>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:id="@+id/text_id"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

本文地址:https://blog.csdn.net/Sun_Sees_You/article/details/107497711

相关标签: android studio java