【问题标题】:TextView background with space between linesTextView 背景与行之间的空间
【发布时间】:2016-02-19 22:17:54
【问题描述】:

我想创建一个带有彩色背景和每行之间的空格的 TextView,链接这个:

我正在尝试使用 SpannableString,但我无法在行之间创建透明空间,知道吗?

谢谢大家,抱歉我的英语不好。

【问题讨论】:

  • 使用 android:lineSpacingExtra

标签: android textview


【解决方案1】:

尝试在您的 XML 文件中使用 lineSpacingExtralineSpacingMultiplier

【讨论】:

  • 我试过了,但是这个属性我无法实现透明背景
【解决方案2】:

如果我没记错的话,你想在 TextView 中添加一个透明的新行吗?

这对于单个 TextView 是不可能的,因为 SpannableString 只会影响 TextView 的内容,并且 Textview 的背景与 TextView 的内容不同。 如果您必须实现这一点,那么您必须为 TextView 提供自定义实现,当在文本内容中找到新行时,它将在 onDraw 方法中为您的自定义视图绘制透明背景。

或者其他选项是为每一行文本呈现一个新的文本视图。

【讨论】:

    【解决方案3】:

    您好,应该在布局中动态添加 textview,此时您必须设置 textview 的属性。您可以这样做

    TvEx.java

    public class TvEx extends Activity {
    LinearLayout llMain;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tv_ex);
        llMain = (LinearLayout) findViewById(R.id.llmainTvEx);
    
        final int N = 10; // total number of textviews to add
    
        final TextView[] myTextViews = new TextView[N]; // create an empty
                                                        // array;
    
        for (int i = 0; i < N; i++) {
            // create a new textview
            final TextView rowTextView = new TextView(this);
            LinearLayout.LayoutParams buttonLayoutParams = new  LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            buttonLayoutParams.setMargins(100, 20, 0, 0); // Set margins here
            // set some properties of rowTextView or something
            rowTextView.setText("This is row #" + i);
            rowTextView.setBackgroundColor(Color.WHITE);
            rowTextView.setLayoutParams(buttonLayoutParams);
            // add the textview to the linearlayout
            llMain.addView(rowTextView);
            // save a reference to the textview for later
            myTextViews[i] = rowTextView;
         }
       }
    }
    

    tv_ex.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="match_parent"
       android:id="@+id/llmainTvEx"
       android:layout_height="match_parent"
       android:background="#A75653"
       android:orientation="vertical"></LinearLayout>
    

    【讨论】:

    • 使用此代码,您可以动态添加 Textview 并为其设置属性,只要有换行符,您就可以将其视为新字符串并且可以执行您想要的操作。
    • 如何将文本分行?
    • 但是我需要根据可用空间的宽度来分割字符串
    • 它是动态的,它来自网络服务
    猜你喜欢
    • 2022-12-23
    • 2016-01-07
    • 2017-11-25
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    相关资源
    最近更新 更多