Android TextView同时设置粗体和斜体
效果图
问题
TextView的粗体和斜体无法同时生效,要么显示斜体,要么显示粗体。
错误代码:
tv_test3.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
tv_test3.setTypeface(Typeface.SANS_SERIF, Typeface.ITALIC);
正确示例:
tv_test3.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD_ITALIC);
参考完整代码
Activity
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView tv_test1;
private TextView tv_test2;
private TextView tv_test3;
private TextView tv_test4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_test1 = findViewById(R.id.tv_test1);
tv_test2 = findViewById(R.id.tv_test2);
tv_test3 = findViewById(R.id.tv_test3);
tv_test4 = findViewById(R.id.tv_test4);
tv_test1.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
tv_test2.setTypeface(Typeface.SANS_SERIF, Typeface.ITALIC);
tv_test3.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
tv_test3.setTypeface(Typeface.SANS_SERIF, Typeface.ITALIC);
tv_test4.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD_ITALIC);
}
}
layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv_test1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="粗体"
android:textSize="20dp" />
<TextView
android:id="@+id/tv_test2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="斜体"
android:textSize="20dp" />
<TextView
android:id="@+id/tv_test3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="粗体+斜体"
android:textSize="20dp" />
<TextView
android:id="@+id/tv_test4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="粗体+斜体"
android:textSize="20dp" />
</LinearLayout>