首页 > 解决方案 > 使用自定义按钮 android 填充 gridview

问题描述

我想用我创建的自定义按钮填充网格视图,问题是我不知道这个适配器是如何工作的。

这就是我想要实现的目标

在此处输入图像描述

这是我的自定义 button.java

    public class Items extends Button {
        private final static int WIDTH_PADDING = 10;
        private final static int HEIGHT_PADDING = 10;
        private final String label;
        private final String name;
        private final double price;

        public Items(Context context, String name, double price) {
            super(context);
            this.name = name;
            this.price = price;
            this.label = name;

            setHeight(100);
            setWidth(100);
            setFocusable(true);
            setBackgroundColor(Color.parseColor("#eef771"));
            setClickable(true);
        }

        protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
            super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
            if(gainFocus == true) {
                this.setBackgroundColor(Color.parseColor("#ced662"));
            } else {
                this.setBackgroundColor(Color.parseColor("#eef771"));
            }

        }

        protected void onDraw(Canvas canvas) {
            Paint textPaint = new Paint();
            textPaint.setColor(Color.parseColor("#f4426e"));
            canvas.drawText(label + " (P" + price + ")", (WIDTH_PADDING / 2), (HEIG

HT_PADDING / 2,  textPaint);
    }
}

我的适配器仍然是这样的:

public class ItemsAdapter extends BaseAdapter {
    private Context context;

    public ItemsAdapter(Context context) {
        this.context = context;
    }

    @Override
    public int getCount() {
        return 0;
    }

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

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        return null;
    }
}

我的问题:我希望能够在任何时候向适配器添加自定义按钮,我在这里使用 arrayList 吗?如何返回该 arrayList 以便填充我的 gridView?

我是android新手,所以我不知道这些东西是如何工作的。提前致谢。

标签: javaandroidgridview

解决方案


我建议你先阅读这个Android 开发者主题。您应该使用 RecyclerView 组件来创建此屏幕,因为它比常规 ListView 更加优化和改进。阅读此 Android 开发者主题后,您可以浏览此博文。正如您在图片中展示的那样,有一个如何制作这种屏幕的示例。但请务必充分了解此 RecyclerView.Adapter 的工作原理以及与 RecyclerView.ViewHolder 对象的关系。


推荐阅读