首页 > 解决方案 > 以特定方式对齐 TextView

问题描述

我目前正在学习 Android 中的一些技术,我想通过按下按钮(通过 Java)将 TextViews 添加到应用程序(视图)中。但在通过代码添加它们之前,我想从"res/values/styles.xml"TextView为每个附加一个自制的预配置样式。这是迄今为止的主要思想。

基本上我想知道如何在 Activity 的 XML 文件中配置我的 TextViews(在 styles.xml 中)和给定的布局(例如 main_activity.xml),以便它们看起来像这张图片:

像这样

所以目标是以这样一种方式预先配置布局和文本视图,我只需要一个接一个地添加文本视图,以便它们以如图中的方式对齐。

为了实现这一目标,我必须做什么?

// main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    ...>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView style="@style/AddedTextView" />

    </RelativeLayout>
    
    ...

    <Button
        android:id="@+id/btn_add"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button" />
</LinearLayout>

// res/values/styles.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AddedTextView" parent="Widget.AppCompat.TextView">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:background">@drawable/custom_textview_design</item>
        <item name="android:text">TestTV</item>
        <item name="android:textColor">@color/common_text_color</item>
        <item name="android:textSize">7pt</item>
        <item name="android:layout_alignParentLeft">true</item>
    </style>
</resources>

标签: androidandroid-layoutuser-interfacelayouttextview

解决方案


您可以使用以下方式以编程方式应用样式ContextThemeWrapper

val textView = TextView(ContextThemeWrapper(this, R.style.AddedTextView))

要添加TextView相互连接的 s 并将它们垂直包装,您可以使用 Google 的FlexBoxLayout

这是基本布局:

<com.google.android.flexbox.FlexboxLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/flexLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:flexDirection="row"
    app:flexWrap="wrap">

</com.google.android.flexbox.FlexboxLayout>

以编程方式添加视图非常简单:

val flexboxLayout = findViewById<View>(R.id.flexLayout) as FlexboxLayout

for (i in 1..50) {
    val textView = TextView(ContextThemeWrapper(this, R.style.AddedTextView))
    val layoutParams = FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
    layoutParams.rightMargin = 40
    textView.layoutParams = layoutParams
    textView.text = "TextView $i"
    flexboxLayout.addView(textView)
}

在此处输入图像描述


推荐阅读