如何设置TextView风格(粗体或斜体)在Java和不使用XML布局?
换句话说,我需要用Java编写android:textStyle。
如何设置TextView风格(粗体或斜体)在Java和不使用XML布局?
换句话说,我需要用Java编写android:textStyle。
当前回答
你可以这样做:
myTextView.setTypeface(null, Typeface.ITALIC);
myTextView.setTypeface(null, Typeface.BOLD_ITALIC);
myTextView.setTypeface(null, Typeface.BOLD);
myTextView.setTypeface(null, Typeface.NORMAL);
如果你想保留之前的字体,不想失去之前应用的字体,那么另一个选择:
myTextView.setTypeface(textView.getTypeface(), Typeface.NORMAL);
myTextView.setTypeface(textView.getTypeface(), Typeface.BOLD);
myTextView.setTypeface(textView.getTypeface(), Typeface.ITALIC);
myTextView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC);
其他回答
textView.setTypeface(null, Typeface.BOLD_ITALIC);
textView.setTypeface(null, Typeface.BOLD);
textView.setTypeface(null, Typeface.ITALIC);
textView.setTypeface(null, Typeface.NORMAL);
保持以前的字体
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC)
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
编程:
你可以通过编程方式使用setTypeface():
textView.setTypeface(null, Typeface.NORMAL); // for Normal Text
textView.setTypeface(null, Typeface.BOLD); // for Bold only
textView.setTypeface(null, Typeface.ITALIC); // for Italic
textView.setTypeface(null, Typeface.BOLD_ITALIC); // for Bold and Italic
XML:
你可以在<TextView />中的XML文件中直接设置如下:
android:textStyle="normal"
android:textStyle="normal|bold"
android:textStyle="normal|italic"
android:textStyle="bold"
android:textStyle="bold|italic"
标准的方法是使用自定义样式。 除
在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" />
基于样式选择标准,最简单的方法是:
String pre = "", post = "";
if(isBold){
pre += "<b>"; post += "</b>";
}
if(isItalic){
pre += "<i>"; post += "</i>";
}
if(isUnderline){
pre += "<u>"; post += "</u>";
}
textView.setText(Html.fromHtml(pre + editText.getText().toString()+ post));
// you can also use it with EidtText
editText.setText(Html.fromHtml(pre + editText.getText().toString()+ post));