麻烦使用SpannableString

时间:2015-05-27 16:22:22

标签: android

我有一种方法可以使用2种颜色制作一个字符串,并将其放入textview中:

public static void makeMenuText(TextView view, String str1, String str2){

    String text = (str1 + " " +str2).trim();
    SpannableString spannable = new SpannableString(text);

    spannable.setSpan(new ForegroundColorSpan(resources.getColor(R.color.textColor)), 0, str1.length(), 0);
    spannable.setSpan(new ForegroundColorSpan(resources.getColor(R.color.mainColor)), str1.length(), text.length(), 0);

    view.setText(spannable);

}

我的文件colors.xml:

<color name="mainColor">#ff9c005a</color>
<color name="textColor">#ff424242</color>

我的textview保留文本的默认颜色,我的错误在哪里?

谢谢

修改

我终于找到了它,我的textview样式中的textallcaps引起了问题,我删除了它并将我的代码更改为:

SpannableString spannable = new SpannableString(text.toUpperCase());

2 个答案:

答案 0 :(得分:0)

Tenta algo assim:

spannable.setSpan(new ForegroundColorSpan(resources.getColor(R.color.textColor)), 0, str1.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new ForegroundColorSpan(resources.getColor(R.color.mainColor)), str1.length(), text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

答案 1 :(得分:0)

Result screenshot attached

XML - 布局文件包含TextView

 <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"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/txtHelloAndroidOne"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="26sp" />

    <TextView
        android:id="@+id/txtHelloAndroidTwo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dip"
        android:textSize="26sp" />

</LinearLayout>

Java类

 public class MainActivity extends Activity {

    private TextView txtHelloAndroidOne, txtHelloAndroidTwo;
    private String colorOne = "#ff9c005a";
    private String colorTwo = "#ff424242";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // bind textview
        txtHelloAndroidOne = (TextView)findViewById(R.id.txtHelloAndroidOne);
        txtHelloAndroidTwo = (TextView)findViewById(R.id.txtHelloAndroidTwo);

        // set colored text on textview
        txtHelloAndroidOne.setText(getColoredSpanned("Hello Android First", Color.parseColor(colorOne)));
        txtHelloAndroidTwo.setText(getColoredSpanned("Hello Android Second", Color.parseColor(colorTwo)));
    }

    private Spanned getColoredSpanned(String text, int color){
        String input = "<font color='" +color+ "'>" + text + "</font>";
        Spanned spannedStrinf = Html.fromHtml(input);
        return spannedStrinf;
    }
}

完成