我正试图创建一个视图,里面有一个文本,将来还要给这个视图添加更多元素。
现在我尝试了几个阅读Stack Overflow上的老帖子,但未能在当前视图中显示文本。
TaskView.java
public class TaskView extends View {
CharSequence text;
public TaskView(Context context, AttributeSet attributes) {
super(context, attributes);
TypedArray typedArray = context.obtainStyledAttributes(
attributes, R.styleable.TaskView);
try {
text = typedArray.getText(R.styleable.TaskView_android_text);
} finally {
typedArray.recycle();
}
}
attrs.xml
<resources >
<declare-styleable name="TaskView">
<attr name="android:text" />
<attr name="android:textSize" />
</declare-styleable>
</resources>
layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:costum="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.application.arjan.notes.Planner.TaskView
android:layout_width="200dp"
android:layout_height="200dp"
android:background="@color/backgroundOrangeLight"
android:text="Hello!!!" **Can't see this text**
android:textSize="20dp"
costum:layout_constraintBottom_toBottomOf="parent"
costum:layout_constraintEnd_toEndOf="parent"
costum:layout_constraintStart_toStartOf="parent"
costum:layout_constraintTop_toTopOf="parent"
android:gravity="center_horizontal">
</com.application.arjan.notes.Planner.TaskView>
</android.support.constraint.ConstraintLayout>
我找不到我的错误,我也试过用服装属性(比如只有文本,没有android),并在attrs属性中加入format=string。当我显示这个视图时,我只看到一个定义了背景色的方块......
你必须在TaskView类中手动绘制你的文本,首先定义你的Paint。
Paint textPaint;
textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textPaint.setColor(textColor);
然后绘制它。
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw the label text
canvas.drawText(text, 0.0, 0.0, textPaint);
}
更多选项请看 正式文件