如何设置TextView风格(粗体或斜体)在Java和不使用XML布局?
换句话说,我需要用Java编写android:textStyle。
如何设置TextView风格(粗体或斜体)在Java和不使用XML布局?
换句话说,我需要用Java编写android:textStyle。
当前回答
试试这个:
TextView textview = (TextView)findViewById(R.id.textview_idname);
textview.setTypeface(null,Typeface.BOLD);
其他回答
//leveraging the extension functions
fun TextView.makeBold(){
this.setTypeface(this.typeface,Typeface.BOLD)
}
yourTextView.makeBold()
AppCompatTextView text =(AppCompatTextView)findViewById(R.layout.appCompatTextView1);
text.setTypeface(null,Typeface.BOLD);
使用上述方法以编程方式设置字体。
你有两个选择:
选项1(只适用于粗体、斜体和下划线):
String s = "<b>Bolded text</b>, <i>italic text</i>, even <u>underlined</u>!"
TextView tv = (TextView)findViewById(R.id.THE_TEXTVIEW_ID);
tv.setText(Html.fromHtml(s));
选项2:
使用可伸缩帆布;它更复杂,但您可以动态修改文本属性(不仅是粗体/斜体,还包括颜色)。
您可以使用下面给出的示例设置不同的字体-
textView.setTypeface(textView.getTypeface(), Typeface.BOLD);
textView.setTypeface(textView.getTypeface(), Typeface.ITALIC);
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC);
或者如果你想设置一个不同的字体和它的字体。将其添加到资产或原始文件夹,然后像这样使用它
Typeface face= Typeface.createFromAsset(getAssets(), "font/font.ttf");
tv1.setTypeface(face);
Typeface face1= Typeface.createFromAsset(getAssets(), "font/font1.ttf");
tv2.setTypeface(face1);
这是我在配置了OnePlus Slate™字体的OnePlus 5T上唯一有效的功能:
textView.setTypeface(Typeface.create(textView.getTypeface(), useBold ? Typeface.BOLD : Typeface.NORMAL));
其他方法将使它在BOLD或NORMAL时回落到Roboto。