gpt4 book ai didi

旁边有文字的Android自定义按钮

转载 作者:太空狗 更新时间:2023-10-29 13:33:37 25 4
gpt4 key购买 nike

我正在尝试创建一个旁边带有文本的自定义按钮。我将有一个旁边带有 (x) 的项目列表,因此用户可以点击 (x) 删除该项目。像这样...

(x)项目 1 (x)项目 2 (x)项目 3

我有一个扩展按钮的类,但我不确定应该覆盖哪些方法,因为当我使用自定义类创建按钮时,它显示为普通按钮。这是我的代码。

public class LabelButton extends Button {
private final Context context;

private final String label;

public LabelButton( Context context, String label ) {
super( context );
this.context = context;
this.label = label;
}

public View getView( View convertView, ViewGroup parent ) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View labelView = inflater.inflate( R.layout.label, parent, false );
TextView textView = (TextView) labelView.findViewById( R.id.label );
Button button = (Button) labelView.findViewById( R.id.buttonCancel );
textView.setText( "X" );
return labelView;
}

最佳答案

您应该使用 Attrs 参数覆盖 onDraw 方法和构造函数

 public LabelButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if (attrs != null) {
// set your attrs
}
}

@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint textPaint = new Paint();
textPaint.setAntiAlias(true);
textPaint.setColor(textColor);
textPaint.setTextSize(textSize);
Rect bounds = new Rect();
textPaint.getTextBounds(totalText, 0, totalText.length(), bounds);
int x = getWidth() / 2 - bounds.centerX();
int y = getHeight() / 2 - bounds.centerY();
canvas.drawText(text, getLeft(), y, textPaint);// draw your text in coords
}

public synchronized void setText(String text) {
if (text != null) {
this.text = text;
} else {
this.text = "";
}
postInvalidate();
}

关于旁边有文字的Android自定义按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13031166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com