如何设置TextView风格(粗体或斜体)在Java和不使用XML布局?

换句话说,我需要用Java编写android:textStyle。


当前回答

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

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);

其他回答

试试这个:

textView.setTypeface(textView.getTypeface(), Typeface.BOLD);
textView.setTypeface(textView.getTypeface(), Typeface.ITALIC);
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC);

试着在TextView上设置粗体或斜体

textView.setTypeface(textView.getTypeface(), Typeface.BOLD);
textView.setTypeface(textView.getTypeface(), Typeface.ITALIC);
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC);

这是我在配置了OnePlus Slate™字体的OnePlus 5T上唯一有效的功能:

textView.setTypeface(Typeface.create(textView.getTypeface(), useBold ? Typeface.BOLD : Typeface.NORMAL));

其他方法将使它在BOLD或NORMAL时回落到Roboto。

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)
//leveraging the extension functions
fun TextView.makeBold(){
    this.setTypeface(this.typeface,Typeface.BOLD)
}


yourTextView.makeBold()