I am developing an application with a custom font, setting the typeface is working fine, but I was wondering is there a better a way to set TypeFace to all the editTexts in my activity than put in them one by one. This is how I'm doing it actually:

Typeface font = Typeface.createFromAsset(this.getAssets(),"fonts/NeoSans.otf");
Typeface fontBold = Typeface.createFromAsset(this.getAssets(),"fonts/NeoSans-Bold.otf");


    edt_txt_nombre = (EditText) findViewById(R.id.edt_nombres);
    edt_txt_apellido = (EditText) findViewById(R.id.edt_apellidos);
    edt_txt_usuario = (EditText) findViewById(R.id.edt_usuario);
    edt_txt_contrasena = (EditText) findViewById(R.id.edt_contrasena);
    edt_txt_email = (EditText) findViewById(R.id.edt_email);
    edt_txt_telefono = (EditText) findViewById(R.id.edt_telefono);
    edt_txt_fecha = (EditText) findViewById(R.id.edt_fec_nac);

    registrar.setTypeface(fontBold);
    txt_nombre.setTypeface(font);
    txt_apellido.setTypeface(font);     
    txt_telefono.setTypeface(font);
    txt_fecha.setTypeface(font);
    edt_txt_nombre.setTypeface(font);
    edt_txt_apellido.setTypeface(font);
    edt_txt_usuario.setTypeface(font);
    edt_txt_contrasena.setTypeface(font);
    edt_txt_email.setTypeface(font);
    edt_txt_telefono.setTypeface(font);
    edt_txt_fecha.setTypeface(font);

Is it a better (shorter) way to do it?

有帮助吗?

解决方案

You could subclass EditText and set the typeface in the constructor:

public class MyEditText extends EditText {

    // replace '...' with proper arguments
    public MyEditText(...) {
        super(...)
        // fetch your font
        this.setTypeface(myFont);
    }
}

Don't forget the EditText(Context context, AttributeSet attrs) and EditText(Context context, AttributeSet attrs, int style) constructors in your subclass or your layout will fail to inflate.

Then in your layout.xml, refer to your new MyEditText subclass instead:

<com.myapp.MyEditText
    ... />
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top