SpannableStringBuilder to create String with multiple fonts/text sizes etc Example?

后端 未结 9 1528
眼角桃花
眼角桃花 2020-11-28 03:00

I need to create a String placed in a TextView that will display a string like this:

First Part Not Bold BOLD rest not bold

9条回答
  •  独厮守ぢ
    2020-11-28 03:52

    So I know this has been solved, and even as requested with SpannableStringBuilder but in the event you wanted to build a string more dynamically I figured I would put this up.

    // Stuff needed
    TextView DataTextView = (TextView)rootView.findViewById(R.id.DataView);
    String Fields[] = {...database column names as strings... "x","y"};
    
    String DataString = new String();   
    
    int start,stop;     // Start and Stop of formatting
    
    // Final Result
    SpannableStringBuilder coloredString = new SpannableStringBuilder(); 
    
    SpannableString temp;       // Small segment of colored string
    for (int i =0; i < Fields.length; i++)
    {
        if (database_result.containsKey(Fields[i]))  // Be sure a field exists in the ContentValues
        {
                DataString = Fields[i]+": ";
            start = DataString.length();
            DataString = DataString+ +database_result.getAsInteger(Fields[i])+" ";
            stop= DataString.length();
            temp = new SpannableString(DataString);
            temp.setSpan(new ForegroundColorSpan(Color.WHITE),start, stop, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            coloredString.append(temp);
        }   
    }
    DataTextView.setText(coloredString);
    

    database_result is a ContentValues type that I constructed from the returned Cursor type of the SQL query. The only problem I had with this was at first it was only ColorSpaning the first segment. It seams that you need to declare a new ForegroundColorSpan every time you want to use one (or any other kind of span) in a loop.

提交回复
热议问题