【问题标题】:Can we set two gravity for single textview我们可以为单个文本视图设置两个重力吗
【发布时间】:2017-01-24 18:53:20
【问题描述】:

我必须为单个 TextView 设置两个重力是否可能

类似这样,

  This line is example|
      Center Text     |
             I m right|

我必须在单个 TextView 中实现这一点,所以请不要建议我声明两个 textview 一个具有 TextView1 CENTER 重力和另一个 TextView2 具有 RIGHT 重力。

是否可以使用 Span 或 Html 或任何其他属性。

【问题讨论】:

  • 投反对票请解释
  • 我猜你可以使用<div align = "...">。请参阅supported HTML tags in TextViews(感谢@CommonsWare 提供列表)。但是……为什么不使用WebView?它将为您提供更完整的 HTML 支持。

标签: android


【解决方案1】:

使用 Spannable 解决问题

spannablecontent.setSpan(new AlignmentSpan.Standard( Layout.Alignment.ALIGN_OPPOSITE), 0, 15, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

对于单个 TextView,我们可以将其分配为

左 = ALIGN_NORMAL

中心 = ALIGN_CENTER

右 = ALIGN_OPPOSITE 。

【讨论】:

    【解决方案2】:

    如果您只想要一个单一的文本视图,使用 HTML 将为您提供解决方案。我把它贴在下面了。

    activity_main

     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".MainActivity"
            android:orientation="vertical" >
            <TextView
                android:id="@+id/html_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
    
        </LinearLayout>
    

    MainActivity.java

    import android.os.Bundle;
    import android.app.Activity;
    import android.text.Html;
    import android.widget.TextView;
    
    public class MainActivity extends Activity {
    
        private final String htmlText = "<body><p>This line is example|  " +"<br>"+ 
                "&nbsp;&nbsp;&nbsp;&nbsp;Center Text&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|" +"<br>"+
                "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;I am right|";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            TextView htmlTextView = (TextView)findViewById(R.id.html_text);
            htmlTextView.setText(Html.fromHtml(htmlText));
    
        }
    
    
    }
    

    现在您可以使用 HTML 更改文本颜色或任何您喜欢的内容

    【讨论】:

    • 你应该如何计算在多个屏幕分辨率上居中或右对齐文本需要多少空间?顺便说一句,如果使用这种可怕的方法,你甚至根本不需要 HTML。
    猜你喜欢
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 2021-01-11
    • 2022-08-04
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    • 1970-01-01
    相关资源
    最近更新 更多