【问题标题】:How to put 2 customViews inside a dynamic RelativeLayout?如何将 2 个 customViews 放入动态 RelativeLayout?
【发布时间】:2019-10-22 06:00:51
【问题描述】:

我收到了以下customViews

val paintTextTypology = Paint()
val paintTextDate = Paint()

这2个文本是以下customViews

而我想要达到的结果是这样的:

所以我想将文本向右对齐,但由于文本是分开的,我想我必须创建一个动态的RelativeLayout 来将它们对齐到父级的右侧。 (我买不起margin-right,因为文本可以更改。) 我该怎么做?

【问题讨论】:

  • 嗨佩德罗,我认为你需要对你想要达到的目标提供一些更好的解释。第一个建议是:不要使用相对布局。立即使用 ConstraintLayout。
  • 嗨。是的,我可以使用约束布局,但是如何动态创建一个,然后将 2 个自定义视图放入其中?只有这样我才能将它们联系起来......谢谢@MartinMarconcini

标签: android kotlin android-custom-view android-relativelayout custom-view


【解决方案1】:

根据您的评论(我还不是 100% 清楚,因为我不知道您的 自定义视图 是什么),我将使用如下所示的 ConstraintLayout:

红色矩形是您的图片。 然后我添加了两个与图像对齐的文本视图。你可以玩它,看看你还需要什么。 (这是一种简化)。

<?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"
    >
    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is textView One"
        app:layout_constraintEnd_toStartOf="@id/image"
        app:layout_constraintTop_toTopOf="@+id/image"
        />
    <TextView
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is textView Two -> longer"
        app:layout_constraintEnd_toStartOf="@id/image"
        app:layout_constraintTop_toBottomOf="@id/text1"
        />
    <ImageView
        android:id="@+id/image"
        android:layout_width="150dp"
        android:layout_height="300dp"
        android:contentDescription="TODO"
        android:src="@color/emphasis_red"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />
</android.support.constraint.ConstraintLayout>

看起来像这样:

【讨论】:

  • 不能在 XML 中...应该全部在 kotlin 中,因为都应该在 onDraw(canvas: Canvas) 函数中
  • 除非您有充分的理由使用画布和 Paint 对象绘制文本,否则我建议您改为使用 TextViews 创建一个从 XML 扩展的自定义视图。您想要这样做的原因之一是因为它会为您解决这个问题;当您绘制到 Canvas 时,没有边距、字距调整、RTL 支持等。您只需在画布上绘制一条路径。
猜你喜欢
  • 2015-10-25
  • 2011-03-30
  • 1970-01-01
  • 2015-09-26
  • 1970-01-01
  • 1970-01-01
  • 2013-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多