如何设置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); 

其他回答

正如这里所解释的,如果你需要在你的样式文本资源中使用参数,你必须转义开括号

<resources>
<string name="welcome_messages">Hello, %1$s! You have &lt;b>%2$d new messages&lt;/b>.</string>
</resources>

然后调用formatHtml(string)

Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
CharSequence styledText = Html.fromHtml(text);

您可以使用下面给出的示例设置不同的字体-

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);
AppCompatTextView text =(AppCompatTextView)findViewById(R.layout.appCompatTextView1);
text.setTypeface(null,Typeface.BOLD);

使用上述方法以编程方式设置字体。

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 textview = (TextView)findViewById(R.id.textview_idname);
textview.setTypeface(null,Typeface.BOLD);