android - Android 中可以更改 Edittext、Radio Button 和 CheckBox 的字体类型吗

标签 android checkbox radio-button android-edittext

我是 android 的初学者。我可以在 Android 中更改 Textview 的字体类型。但是我必须使用 asset 文件夹中的 .ttf 文件来进行这种字体更改。

TextView text = (TextView) layout.findViewById(R.id.text);
text.setText(msg);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/handsean.ttf");
text.setTypeface(font); 

上面的代码是我用来更改 TextView 的字体的。但是我还需要更改单选按钮、编辑文本和复选框(我在我的应用程序中也使用过)的文本的字体类型。请在这里帮助我。在此先感谢。

最佳答案

所选答案缺少代码,所以这里是:

编辑文本

EditText editText = (EditText) layout.findViewById(R.id.edittext);
editText.setText(msg);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");
editText.setTypeface(font);

单选按钮

RadioButton radioButton = (RadioButton) layout.findViewById(R.id.radiobutton);
radioButton.setText(msg);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/myfont.ttf");
radioButton.setTypeface(font);

复选框

CheckBox checkBox = (CheckBox) layout.findViewById(R.id.checkbox);
checkBox.setText(msg);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");
checkBox.setTypeface(font);

多个 View

如果您需要为应用程序中的多个 View 执行此操作,那么创建 EditTextRadioButtonCheckBox 的子类可能会更容易。这个子类设置字体。以下是 CheckBox 的示例。

public class MyCheckBox extends CheckBox {

    // Constructors
    public MyCheckBox(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }
    public MyCheckBox(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    public MyCheckBox(Context context) {
        super(context);
        init();
    }

    // This class requires myfont.ttf to be in the assets/fonts folder
    private void init() {
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
                "fonts/myfont.ttf");
        setTypeface(tf);
    }
}

可以在xml中使用如下:

<com.example.projectname.MyCheckBox
    android:id="@+id/checkbox"
    android:text="@string/msg"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:checked="true"/>

关于android - Android 中可以更改 Edittext、Radio Button 和 CheckBox 的字体类型吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9390460/

相关文章:

android - 在单选组 Android 中手动管理单选按钮

java - 如何在 Gowalla Java (Android) 中获取访问 token

java - 通过反射改变 colorPrimary 和 colorAccent

android - CheckBox 如何获取其各自的可绘制对象?

c# - 通过 JQuery 检查复选框时,复选框 OnCheckedChanged 不会触发

javascript - AngularJS 上的单选框选定项目

javascript - 选择了哪个单选按钮?模态结果显示

android - 从线性布局以编程方式设置两个按钮之间的边距

android - 在 Android 4.4 上运行 Espresso 测试?

android - 我可以在 android 的线性布局中声明这种类型的动态复选框吗?