android - 以特定方式对齐 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>
解决方案
您可以使用以下方式以编程方式应用样式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)
}
推荐阅读
- xml - 甲骨文集合
- azure - 如何避免多个 azure B2C 用户会话
- javascript - 在chrome上打开问题后,物化日期选择器自动隐藏
- javascript - JavaScript 从网络路径获取图像
- javascript - 通过javascript函数导入文本
- javascript - 如何通过 Discord Bot 让 Webhook 说话(循环)
- vb.net - VB.NET 服务器不接收来自远程客户端的连接请求
- php - 如何防止为在 Laravel 中同时处理的请求创建多个条目
- .net - 在 Windows 10 IOT 上运行的 .net Core 3 是否可以与 WPF 一起使用?
- node.js - Nest JS - 为返回 Observable Axios 响应的函数编写 Jest 测试用例的问题