Выравнивание текстового представления с макетом ограничения - PullRequest
1 голос
/ 26 марта 2019

Я пытаюсь выровнять текстовое представление в макете ограничения без использования полей, чтобы макет мог быть адаптивным на всех устройствах, но пока я застрял в позиционировании. Вот мой код и ожидаемый вывод, прикрепленный к изображению. Я просто хочу, чтобы сумма немного выровнялась с текстом валюты. This is the expected output

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

     <TextView
         android:id="@+id/year_bar_chart_total"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="Total"
         app:layout_constraintStart_toStartOf="parent"
         app:layout_constraintTop_toTopOf="parent"
         />
     <TextView
         android:id="@+id/yearBarChartCurrency"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="RM"
         app:layout_constraintEnd_toEndOf="@+id/yearBarChartAmount"
         app:layout_constraintHorizontal_bias="0.17"
         app:layout_constraintStart_toStartOf="@id/year_bar_chart_total"
         app:layout_constraintTop_toBottomOf="@id/year_bar_chart_total"
         tools:text="RM"/>
     <TextView
         android:id="@+id/yearBarChartAmount"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="tOTAL"
         app:layout_constraintHorizontal_bias="0.17"
         app:layout_constraintStart_toEndOf="@id/yearBarChartCurrency"
         app:layout_constraintTop_toBottomOf="@id/year_bar_chart_total"
         tools:text="233.34"/>

</android.support.constraint.ConstraintLayout>

Ответы [ 2 ]

1 голос
/ 26 марта 2019

Полагаю, вы хотите выровнять верх текста.

A TextView имеет внутреннюю структуру, основанную на типографии шрифта. «Android 101: Типография» содержит хорошее объяснение типографии Android. Эта диаграмма особенно полезна.

Итак, следующий макет выглядит так в режиме конструктора. Как видите, верхние части текста не совпадают.

enter image description here

activity_main.xml

<android.support.constraint.ConstraintLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#4778C5"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/year_bar_chart_total"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:alpha="0.7"
        android:text="Balance"
        android:textColor="@android:color/white"
        android:textSize="24sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/yearBarChartCurrency"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="RM"
        android:textColor="@android:color/white"
        android:textSize="24sp"
        app:layout_constraintStart_toStartOf="@+id/year_bar_chart_total"
        app:layout_constraintTop_toBottomOf="@+id/year_bar_chart_total"
        tools:text="RM" />

    <TextView
        android:id="@+id/yearBarChartAmount"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingStart="4sp"
        android:paddingLeft="4sp"
        android:text="233.34"
        android:textColor="@android:color/white"
        android:textSize="36sp"
        android:textStyle="bold"
        app:layout_constraintStart_toEndOf="@+id/yearBarChartCurrency"
        app:layout_constraintTop_toTopOf="@+id/yearBarChartCurrency" />

</android.support.constraint.ConstraintLayout>

Несмотря на то, что шрифты TextViews одинаковы, различные размеры шрифтов препятствуют выравниванию вершин реального текста, даже если у TextViews их вершины совмещены. Это потому, что показатели отличаются.

Итак, чтобы выровнять фактические вершины текста, нам нужно определить, как далеко под TextView вершинами начинается фактический текст, и сместить текст на эти суммы. Следующий код делает это. Комментарии в коде.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView yearBarChartAmount = findViewById(R.id.yearBarChartAmount);
        TextView yearBarChartCurrency = findViewById(R.id.yearBarChartCurrency);
        yearBarChartCurrency.setTranslationY(-getTopOfText(yearBarChartCurrency));
        yearBarChartAmount.setTranslationY(-getTopOfText(yearBarChartAmount));
    }

    private int getTopOfText(TextView textView) {
        // Force measure of text pre-layout.
        textView.measure(0, 0);
        String s = (String) textView.getText();

        // bounds will store the rectangle that will circumscribe the text.
        Rect bounds = new Rect();
        Paint textPaint = textView.getPaint();

        // Get the bounds for the text. Top and bottom are measured from the baseline. Left
        // and right are measured from 0.
        textPaint.getTextBounds(s, 0, s.length(), bounds);
        int baseline = textView.getBaseline();
        bounds.top = baseline + bounds.top;
        return bounds.top;
    }
}

Отображается следующее:

enter image description here

Могут быть и другие соображения, но это суть решения. Возможно, стоит включить это в пользовательский TextView.

1 голос
/ 26 марта 2019

Вы можете использовать руководящие принципы для достижения этой цели:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<androidx.constraintlayout.widget.Guideline
    android:id="@+id/guideline2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.1" />

<androidx.constraintlayout.widget.Guideline
    android:id="@+id/guideline3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.1" />

<androidx.constraintlayout.widget.Guideline
    android:id="@+id/guideline4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.25" />

<TextView
    android:id="@+id/textView4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="balance"
    app:layout_constraintBottom_toTopOf="@+id/textView5"
    app:layout_constraintStart_toStartOf="@+id/guideline3" />

<TextView
    android:id="@+id/textView5"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="RM"
    app:layout_constraintBottom_toTopOf="@+id/guideline2"
    app:layout_constraintStart_toStartOf="@+id/guideline3" />

<TextView
    android:id="@+id/textView8"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="233.34"
    app:layout_constraintEnd_toStartOf="@+id/guideline4"
    app:layout_constraintStart_toEndOf="@+id/textView5"
    app:layout_constraintTop_toBottomOf="@+id/textView4" />

Это будет выглядеть так:

enter image description here

Я должен подчеркнуть одну вещь, которая действительно беспокоила меня:

«поля, чтобы макет мог реагировать на всех устройствах» - это не так, и позвольте мне объяснить.

что делает ваш экран отзывчивым на все размеры экрана: constraintLayout и как вы его используете, я согласен, что большое количество полей в dp сделает ваш экран не отзывчивым , но в дизайне материалов Google рекомендуется использовать небольшие поля - это фактически улучшит внешний вид вашего приложения и предотвратит привязку ваших просмотров непосредственно к родительской границе.

...