[英]Android custom button with text beside it
I'm trying to create a custom button with text beside it. 我正在尝试创建一个旁边有文字的自定义按钮。 I'm going to have a list of items with a (x) beside them, so the user can hit the (x) to delete the item. 我将在它们旁边有一个带有(x)的项目列表,因此用户可以点击(x)删除该项目。 Like this... 像这样...
(x)Item1 (x)Item2 (x)Item3 (x)项目1(x)项目2(x)项目3
I have a class that extends button, but I'm not sure what methods I'm supposed to override, because when I create a button using the custom class, it shows up as a normal button. 我有一个扩展按钮的类,但我不确定我应该覆盖哪些方法,因为当我使用自定义类创建一个按钮时,它会显示为普通按钮。 Here's my code. 这是我的代码。
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;
}
} }
You could create a custom view that extends LinearLayout, then inflate a xml with a horizontal LinearLayout containing a Button and a TextView. 您可以创建一个扩展LinearLayout的自定义视图,然后使用包含Button和TextView的水平LinearLayout为xml充气。 I suggest creating styled attributes like this tutorial for customization. 我建议创建样式属性,如本教程中的自定义。
You should override onDraw method and constructor with Attrs params 您应该使用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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.