Текст в пользовательском представлении в Android Studio? - PullRequest
0 голосов
/ 25 апреля 2020

Я пытаюсь создать представление с текстом в нем и в будущем добавить к нему больше элементов.

Теперь я попробовал несколько вещей, читая старые сообщения в Переполнение стека, но не смог отобразить текст в моем текущем виде.

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>

* макет 1015 *. 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>

Я не могу найти свою ошибку, я также пытался использовать свойства costum (например, только текст, без android) и добавив format = string в собственность attrs. Когда я отображаю это представление, я вижу только квадрат с заданным фоновым цветом ...

1 Ответ

0 голосов
/ 26 апреля 2020

Вы должны нарисовать свой текст вручную внутри класса TaskView. Сначала определите свою краску:

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);
}

Дополнительные параметры см. В официальных документах

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...