TextView tv = (TextView) View.inflate(parent.getContext(), itemResId, null);
                            tv.setPadding(11 * oneDp, 7 * oneDp, 11 * oneDp, 7 * oneDp);
                            {
                                GradientDrawable drawableDefault = new GradientDrawable();

                                drawableDefault.setShape(GradientDrawable.RECTANGLE);
                                drawableDefault.setCornerRadius(16 * oneDp);
                                drawableDefault.setStroke(oneDp / 2, ContextCompat.getColor(parent.getContext(), R.color.user_tag_gray_line_color));
                                drawableDefault.setColor(ContextCompat.getColor(parent.getContext(), android.R.color.transparent));

                                GradientDrawable drawableChecked = new GradientDrawable();
                                drawableChecked.setShape(GradientDrawable.RECTANGLE);
                                drawableChecked.setCornerRadius(16 * oneDp);
                                drawableChecked.setColor(colorSelectedBg);

                                StateListDrawable stateListDrawable = new StateListDrawable();
                                stateListDrawable.addState(new int[]{android.R.attr.state_checked}, drawableChecked);
                                stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, drawableChecked);

                                stateListDrawable.addState(new int[]{}, drawableDefault);
                                tv.setBackground(stateListDrawable);
                            }
                            tv.setText(tag);

注意点

  1. stateListDrawable.addState(new int[]{}, drawableDefault); 放到addState的最后;
  2. TextView android.R.attr.state_selected 是无效的,使用checked
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐