【问题标题】:TextView spacing is inconsistent with new line charactersTextView 间距与换行符不一致
【发布时间】:2013-03-25 17:52:57
【问题描述】:

我希望“Hello World”之间的间距等于“Stack Overflow”之间的间距,同时保持“World”和“Stack”之间的间距。 “Hello World”包含在TextView 中,并带有换行符“Hello \n World”。 “堆栈溢出”分为两个 TextView 元素。我知道我可以在 myTextView 的布局中使用 lineSpacingExtra,但这也会在“世界”下方添加不需要的间距。

有没有一种优雅的方法来实现等间距?一个想法是在两个TextView 元素之间拆分“Hello World”,并在我看到换行符时使用正则表达式进行拆分,但这有点小技巧。

布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
        >
    <TextView
            android:id="@+id/textview_wraptext"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            />
    <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Stack"
            />
    <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Overflow"
            />
</LinearLayout>

Java 代码:

package com.example.TextViewSpacingExample;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class TextViewSpacing extends Activity {

    private TextView myTextView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        myTextView = (TextView) findViewById(R.id.textview_wraptext);
        myTextView.setText("Hello \nWorld");
    }
}

【问题讨论】:

  • 堆栈和溢出是两个不同的文本视图。你在单个文本视图中打印 Hello World
  • 是的,无论如何我都希望间距相同。
  • 为什么要将字符串拆分为不同的文本视图?也许你真的不需要那个......是否必须动态加载某些字符串而其他字符串是从 xml 设置的?
  • 在我的应用程序的上下文中,这是有道理的。第一个TextView 可以代表一个名字,它作为“名字\n 姓氏”从我的数据库中传递。另外两个TextViews 可能是独立的信息位,例如“婚姻状况”和“最喜欢的冰淇淋”。
  • mmm...将其他信息附加到第一个文本视图怎么样?我仍然不明白需要多个文本视图,除非您想更改视图样式

标签: android textview spacing


【解决方案1】:

我最终将两个“堆栈”和“溢出”TextViews 重新设计为一个 TextView 和一个 SpannableString,因为它是最简单的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    相关资源
    最近更新 更多