ConstraintLayout: 将TextView的顶部与ImageView对齐

6

我尝试通过提供约束条件来使图片和文本视图在约束布局中顶部对齐

<ImageView
    android:id="@+id/img_medal"
    android:layout_width="32dp"
    android:layout_height="32dp"
    android:layout_marginStart="24dp"
    android:layout_marginTop="16dp"
    android:contentDescription="@string/default_content_description"
    android:src="@drawable/medal_gold"
    app:layout_constraintLeft_toLeftOf="@+id/view_award_region"
    app:layout_constraintTop_toTopOf="@+id/view_award_region" />

<TextView
    android:id="@+id/txt_medal_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="0dp"
    android:text="You are gold now."
    app:layout_constraintLeft_toRightOf="@+id/img_medal"
    app:layout_constraintTop_toTopOf="@+id/img_medal"
    style="@style/SettingsMedalTitle"
    />

但是这些视图的顶部会对齐,而不是内容,因为字体的顶部和底部有一些空白空间。有人知道如何解决这个问题吗?(问题可以在下面的图片中看到)

enter image description here


你想让文本与ImageView居中吗? - Akash Dubey
2个回答

0

您需要为txt_medal_title设置一个负的上边距,以使其向屏幕上方移动一点。

有两种方法可以设置此边距的数量。

  • 精确:您需要在代码中进行此操作。将类似于以下内容:
TextView medalTitle = findViewById(R.id.txt_medal_title);
MarginLayoutParams params = (MarginLayoutParams) medalTitle.getLayoutParams();
FontMetrics fm = medalTitle.getPaint().getFontMetrics();
params.topMargin = (int) (fm.top - fm.ascent);
  • 视觉适配:您在布局中使用带有sp单位的负边距值。您将不得不尝试几个不同的值才能获得您想要的结果。请注意,每当更改文本大小或所使用的字体时,都必须重新检查此值。

0

试试这个技巧:

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/img_medal"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginStart="24dp"
        android:layout_marginTop="16dp"
        android:paddingTop="6dp"
        android:contentDescription="@string/app_name"
        android:src="@android:drawable/sym_def_app_icon"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/txt_medal_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:text="You are gold now."
        android:textSize="20sp"
        app:layout_constraintStart_toEndOf="@+id/img_medal"
        app:layout_constraintTop_toTopOf="@+id/img_medal" />

</android.support.constraint.ConstraintLayout>

现在,它看起来就像下面的图片:

enter image description here

希望这对你有所帮助。愉快编码!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接