以编程方式将一个TextView中的不同样式设置为String?

时间:2014-11-10 04:48:33

标签: android string textview styles

我有以下代码在一个TextView中显示两个String。

public View getView(int position, View convertView, ViewGroup parent) {
              System.gc();
              TextView tv = new TextView(mContext.getApplicationContext(), R.);
              String id = null;
              if (convertView == null) {
                    music_column_index = musiccursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
                    musiccursor.moveToPosition(position);
                    id = musiccursor.getString(music_column_index);
                    music_column_index = musiccursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST);
                    musiccursor.moveToPosition(position);
                    id += musiccursor.getString(music_column_index);

                    tv.setText(id));
              } else
                    tv = (TextView) convertView;
              return tv;
        }

我想为两个字符串设置不同的样式。第一。大胆的文字风格

music_column_index = musiccursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
                    musiccursor.moveToPosition(position);
                    id = musiccursor.getString(music_column_index);

二。小文字样式

music_column_index = musiccursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST);
                    musiccursor.moveToPosition(position);
                    id += musiccursor.getString(music_column_index);

有办法吗?

2 个答案:

答案 0 :(得分:0)

是的,请使用:

tv.setTypeface(null, Typeface.BOLD_ITALIC);
tv.setTypeface(null, Typeface.BOLD);
tv.setTypeface(null, Typeface.ITALIC);
tv.setTypeface(null, Typeface.NORMAL);

如果您有2 String,我认为最简单的方法是创建2个单独的TextView并根据您的需要应用上述代码。

<强>更新

  

如果我创建两个单独的TextView,如何返回它?

同样,我能想到的最简单的方法是创建一个List<String> ids并使用它。

所以,请使用:

ids.add(musiccursor.getString(music_column_index));

而不是:

id += musiccursor.getString(music_column_index);

答案 1 :(得分:0)

您可以通过Spannable

执行此操作
music_column_index = musiccursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
musiccursor.moveToPosition(position);
final String title = musiccursor.getString(music_column_index);
id = musiccursor.getString(music_column_index);

music_column_index = musiccursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST);
musiccursor.moveToPosition(position);
id += musiccursor.getString(music_column_index);
final SpannableStringBuilder sb = new SpannableStringBuilder(id);
final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD);
sb.setSpan(bss, 0, title.length, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
tv.setText(sb));

然后你的第一部分将是Bold,第二部分将是正常的。