如何设置TextView风格(粗体或斜体)在Java和不使用XML布局?
换句话说,我需要用Java编写android:textStyle。
如何设置TextView风格(粗体或斜体)在Java和不使用XML布局?
换句话说,我需要用Java编写android:textStyle。
当前回答
标准的方法是使用自定义样式。 除
在styles.xml中添加以下内容。
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="MyApp.TextAppearance.LoginText">
<item name="android:textStyle">bold|italic</item>
</style>
应用此样式到你的TextView如下。
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/MyApp.TextAppearance.LoginText" />
其他回答
试试这个:
TextView textview = (TextView)findViewById(R.id.textview_idname);
textview.setTypeface(null,Typeface.BOLD);
试试这个:
textView.setTypeface(textView.getTypeface(), Typeface.BOLD);
textView.setTypeface(textView.getTypeface(), Typeface.ITALIC);
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC);
你有两个选择:
选项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 text = (TextView)findViewById(R.id.THE_TEXTVIEW_ID);
现在设置textview属性..
text.setTypeface(null, Typeface.BOLD); //-- for only bold the text
text.setTypeface(null, Typeface.BOLD_ITALIC); //-- for bold & italic the text
text.setTypeface(null, Typeface.ITALIC); // -- for italic the text
//leveraging the extension functions
fun TextView.makeBold(){
this.setTypeface(this.typeface,Typeface.BOLD)
}
yourTextView.makeBold()