在自定义字体的文本视图中设置粗体和斜体样式(以编程方式)

时间:2017-06-29 20:19:56

标签: java android fonts

我有一个textview,我希望它是粗体和斜体。我应用我的自定义字体,但只是让我做粗体或斜体。如何将两种样式同时应用于我的textview?

2 个答案:

答案 0 :(得分:1)

您是否尝试过设置XML文件:

android:textStyle="bold|italic"

以编程方式:

textView.setTypeface(yourTypeFace, Typeface.BOLD_ITALIC);

示例:

enter image description here

布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.fontapp.MainActivity">

    <TextView
        android:id="@+id/normal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="16sp"
         />
    <TextView
        android:id="@+id/bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="16sp"
        />
    <TextView
        android:id="@+id/italic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="16sp"
    />
    <TextView
        android:id="@+id/boldItalic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="16sp"
        />
</LinearLayout>

主要活动

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Typeface font = Typeface.createFromAsset(getAssets(), "fonts/bebas_neue_regular.ttf");

        TextView tvNormal = (TextView) findViewById(R.id.normal);
        tvNormal.setTypeface(font);

        TextView tvBold = (TextView) findViewById(R.id.bold);
        tvBold.setTypeface(font, Typeface.BOLD);

        TextView tvItalic = (TextView) findViewById(R.id.italic);
        tvItalic.setTypeface(font, Typeface.ITALIC);


        TextView tvBoth = (TextView) findViewById(R.id.boldItalic);
        tvBoth.setTypeface(font, Typeface.BOLD_ITALIC);
    }
}

答案 1 :(得分:0)

你需要一个粗体和斜体字体,这就是字体的工作方式。不幸的是,Android不能仅仅将它们组合起来,因为它并不那么容易,所以你需要拥有自己的文件。