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

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


当前回答

AppCompatTextView text =(AppCompatTextView)findViewById(R.layout.appCompatTextView1);
text.setTypeface(null,Typeface.BOLD);

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

其他回答

因为我想使用自定义字体,只有几个答案的连接为我工作。显然,设置在我的布局.xml像android:textStlyle="斜体"被AOS忽略。所以最后我不得不这样做: 在strings.xml中,目标字符串声明为:

<string name="txt_sign"><i>The information blah blah ...</i></string>

然后在代码中:

TextView textSign = (TextView) findViewById(R.id.txt_sign);
FontHelper.setSomeCustomFont(textSign);
textSign.setTypeface(textSign.getTypeface(), Typeface.ITALIC);

我没有尝试Spannable选项(我认为必须工作),但是

textSign.setText(Html.fromHtml(getString(R.string.txt_sign))) 

没有效果。同样,如果我从strings.xml中删除斜体标记,只留下setTypeface(),它也没有任何影响。棘手的安卓…

//leveraging the extension functions
fun TextView.makeBold(){
    this.setTypeface(this.typeface,Typeface.BOLD)
}


yourTextView.makeBold()

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

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