安卓实现微信阅读桌面式的网格布局

添加依赖

    //RecyclerView,CardView控件
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    implementation 'com.android.support:cardview-v7:28.0.0'

实体类

public class ModelHomeEntrance {
    private String name = "";
    private Bitmap image;
    private int imageId;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Bitmap getImage() {
        return image;
    }

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

    public int getImageId() {
        return imageId;
    }

    public void setImageId(int imageId) {
        this.imageId = imageId;
    }
}

自定义布局适配器

public class EntranceAdapter extends RecyclerView.Adapter<EntranceAdapter.EntranceViewHolder> {
    private OnItemClickListener onItemClickListener;
    private List<ModelHomeEntrance> mDatas;

    /**
     * 页数下标,从0开始(通俗讲第几页)
     */
    private int mIndex;

    /**
     * 每页显示最大条目个数
     */
    private int mPageSize;

    private Context mContext;

    private List<ModelHomeEntrance> homeEntrances;

    public EntranceAdapter(Context context, List<ModelHomeEntrance> datas, int index, int pageSize) {
        this.mContext = context;
        this.homeEntrances = datas;
        mPageSize = pageSize;
        mDatas = datas;
        mIndex = index;
    }

    @NotNull
    @Override
    public EntranceViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.book_third_list_content, parent, false);//加载布局
        return new EntranceViewHolder(view);
    }

    @Override
    public void onBindViewHolder(EntranceViewHolder holder, final int position) {
        ModelHomeEntrance homeEntrance=homeEntrances.get(position);
        /**
         * 在给View绑定显示的数据时,计算正确的position = position + mIndex * mPageSize,
         */
        final int pos = position + mIndex * mPageSize;
        holder.entranceNameTextView.setText(homeEntrance.getName());
        Log.d("书桌书本名:",homeEntrance.getName());
        holder.entranceIconImageView.setImageBitmap(homeEntrances.get(pos).getImage());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //触发自定义监听的单击事件
                onItemClickListener.onItemClick(holder.itemView, position);
            }
        });
        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                //触发自定义监听的长按事件
                onItemClickListener.onItemLongClick(holder.itemView, position);

                return true;//表示此事件已经消费,不会触发单击事件
            }
        });
    }

    @Override
    public int getItemCount() {
        return mDatas.size() > (mIndex + 1) * mPageSize ? mPageSize : (mDatas.size() - mIndex * mPageSize);
    }

    @Override
    public long getItemId(int position) {
        return position + mIndex * mPageSize;
    }

    class EntranceViewHolder extends RecyclerView.ViewHolder {

        private TextView entranceNameTextView;
        private ImageView entranceIconImageView;

        public EntranceViewHolder(View itemView) {
            super(itemView);
            entranceIconImageView = (ImageView) itemView.findViewById(R.id.bookimage);
            entranceNameTextView = (TextView) itemView.findViewById(R.id.bookname);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams((int) ((float) ScreenUtil.getScreenWidth()/2.9f), (int) ((float) ScreenUtil.getScreenHeight()/3.7f));
            itemView.setLayoutParams(layoutParams);
            LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams((int) ((float) ScreenUtil.getScreenWidth()/3.5f), (int) ((float) ScreenUtil.getScreenHeight()/6.0f));
            entranceIconImageView.setLayoutParams(layoutParams1);
            LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams((int) ((float) ScreenUtil.getScreenWidth()/3.5f), (int) ((float) ScreenUtil.getScreenHeight()/9.0f));
            entranceNameTextView.setLayoutParams(layoutParams2);
        }
    }
    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    /**
     * 自定义监听回调,RecyclerView 的 单击和长按事件
     */
    public interface OnItemClickListener {

        void onItemClick(View view, int position);

        void onItemLongClick(View view, int position);
    }
}

活动中的实现

  private void init() {
        //一共的页数等于 总数/每页数量,并取整。
        int pageCount = (int) Math.ceil(homeEntrances.size() * 1.0 / HOME_ENTRANCE_PAGE_SIZE);
        List<View> viewList = new ArrayList<View>();
        for (int index = 0; index < pageCount; index++) {
            GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity() , 3);
            gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    return 0;
                }
            });
            recycler.setLayoutManager(new GridLayoutManager(getActivity(), 3));
             entranceAdapter= new EntranceAdapter(getActivity(), homeEntrances, index, HOME_ENTRANCE_PAGE_SIZE);
            recycler.setAdapter(entranceAdapter);
            viewList.add(recycler);
            entranceAdapter.setOnItemClickListener(new EntranceAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                
                }
                @Override
                public void onItemLongClick(View view, int position) {
                 AlertDialog alertDialog = new AlertDialog.Builder(Objects.requireNonNull(getActivity()))
                       .setTitle("删除")
                       .setMessage("是否删除?")
                       .setIcon(R.mipmap.ic_launcher)
                       .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialogInterface, int i) {
                           
                       })
                       .setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加取消
                           @Override
                           public void onClick(DialogInterface dialogInterface, int i) {

                           }
                       }).create();
               alertDialog.show();
           }
            });
        }

        }

使用的工具类

public class ScreenUtil {

    static double scale;
    static int screenWidth = 0, screenHeight = 0;

    public static void init(Context context) {
        scale = context.getResources().getDisplayMetrics().density;
        screenWidth = context.getResources().getDisplayMetrics().widthPixels;
        screenHeight = context.getResources().getDisplayMetrics().heightPixels;
    }

    public static int dip2px(float dipValue) {
        return (int) (dipValue * scale + 0.5f);
    }

    public static int px2dip(float pxValue) {
        return (int) (pxValue / scale + 0.5f);
    }

    public static int px2sp(float pxValue) {
        return (int) (pxValue / scale + 0.5f);
    }

    public static int getScreenHeight() {
        return screenHeight;
    }

    public static int getScreenWidth() {
        return screenWidth;
    }
}

自定义布局代码book_third_list_content

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="wrap_content">
    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginHorizontal="4dp"
        android:foreground="?attr/selectableItemBackground"
        app:cardCornerRadius="10dp"
        app:cardUseCompatPadding="true"
        app:contentPadding="5dp">
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <LinearLayout
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
                <ImageView
                    android:id="@+id/bookimage"
                    android:src="@drawable/banner1"
                    android:scaleType="fitXY"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"/>
                <TextView
                    android:paddingTop="5dp"
                    android:id="@+id/bookname"
                    android:gravity="center_horizontal|top"
                    android:text="1"
                    android:textColor="@color/smssdk_black"
                    android:textSize="16sp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </LinearLayout>
            <View
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/selector_trans_divider"/>
        </LinearLayout>
    </androidx.cardview.widget.CardView>
</LinearLayout>

活动中的布局代码

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/Nested"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:descendantFocusability="blocksDescendants"
    android:fillViewport="true"
    android:scrollbars="vertical">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <com.google.android.material.appbar.AppBarLayout
            android:paddingTop="30dp"
            android:background="@color/red"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:popupTheme="@style/AppTheme.PopupOverlay" >
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:gravity="right"
                        android:text="我的图书"
                        android:id="@+id/number"
                        android:textColor="@color/smssdk_black"
                        android:textSize="20sp" />
            </androidx.appcompat.widget.Toolbar>

        </com.google.android.material.appbar.AppBarLayout>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="right"
            android:id="@+id/bookno"
            android:visibility="gone"
            android:textColor="@color/smssdk_black"
            android:textSize="30sp" />
            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/recycler_item_third"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
    </LinearLayout>
</androidx.core.widget.NestedScrollView>
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页