LabelView 示例
时间: 2023-06-24 20:08:46 浏览: 44
以下是一个 LabelView 的示例代码,可以在 Android 平台上使用:
```xml
<com.example.myapp.LabelView
android:id="@+id/label_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:labelBackgroundColor="@color/colorPrimary"
app:labelTextColor="@android:color/white"
app:labelPadding="8dp"
app:labelCornerRadius="4dp" />
```
其中,`LabelView` 是自定义的 View 类,继承自 `TextView`,并添加了一些额外的属性,如 `labelBackgroundColor`、`labelTextColor`、`labelPadding` 和 `labelCornerRadius`。这些属性可以通过在 XML 中设置来改变 LabelView 的样式。
下面是 `LabelView` 类的代码:
```java
public class LabelView extends AppCompatTextView {
private int backgroundColor;
private int textColor;
private int padding;
private int cornerRadius;
public LabelView(Context context) {
super(context);
init(context, null);
}
public LabelView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public LabelView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.LabelView);
backgroundColor = typedArray.getColor(R.styleable.LabelView_labelBackgroundColor, Color.TRANSPARENT);
textColor = typedArray.getColor(R.styleable.LabelView_labelTextColor, Color.BLACK);
padding = typedArray.getDimensionPixelSize(R.styleable.LabelView_labelPadding, 0);
cornerRadius = typedArray.getDimensionPixelSize(R.styleable.LabelView_labelCornerRadius, 0);
typedArray.recycle();
setBackgroundColor(backgroundColor);
setTextColor(textColor);
setPadding(padding, padding, padding, padding);
if (cornerRadius > 0) {
setBackground(createBackgroundDrawable());
}
}
private Drawable createBackgroundDrawable() {
GradientDrawable drawable = new GradientDrawable();
drawable.setColor(backgroundColor);
drawable.setCornerRadius(cornerRadius);
return drawable;
}
public void setBackgroundColor(int backgroundColor) {
this.backgroundColor = backgroundColor;
if (cornerRadius > 0) {
setBackground(createBackgroundDrawable());
} else {
super.setBackgroundColor(backgroundColor);
}
}
public void setLabelTextColor(int textColor) {
this.textColor = textColor;
setTextColor(textColor);
}
public void setLabelPadding(int padding) {
this.padding = padding;
setPadding(padding, padding, padding, padding);
}
public void setLabelCornerRadius(int cornerRadius) {
this.cornerRadius = cornerRadius;
if (cornerRadius > 0) {
setBackground(createBackgroundDrawable());
} else {
super.setBackgroundColor(backgroundColor);
}
}
}
```
在 `init()` 方法中,我们通过获取 XML 中设置的属性值来初始化 LabelView 的样式。如果设置了圆角半径 `cornerRadius`,则创建一个 `GradientDrawable` 并设置为 LabelView 的背景。否则,直接调用 `super.setBackgroundColor()` 方法来设置背景色。同时,我们还提供了一些公开方法,使得使用者可以在代码中动态地改变 LabelView 的样式。