Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

android - Use Roboto font in app with minimum API level 14

I have an app whose minimum API level is 14. Am I correct in thinking all compatible devices should have Roboto font installed as default? If I set a textView font to Roboto or Roboto Light it seems to default to the normal sans typeface.

Is there a way to use Roboto without including the Roboto font as an asset?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Is there a way to use Roboto without including the Roboto font as an asset?

No there is no other way of doing this for API 11<.

I usually create a custom TextView for the Robot typeface:

public class TextView_Roboto extends TextView {

        public TextView_Roboto(Context context, AttributeSet attrs, int defStyle) {
                super(context, attrs, defStyle);
                createFont();
        }

        public TextView_Roboto(Context context, AttributeSet attrs) {
                super(context, attrs);
                createFont();
        }

        public TextView_Roboto(Context context) {
                super(context);
                createFont();
        }

        public void createFont() {
                Typeface font = Typeface.createFromAsset(getContext().getAssets(), "robo_font.ttf");
                setTypeface(font);
        }
}

Now you can use it in your Layouts like this:

<com.my.package.TextView_Roboto>
  android:layout_width="..."
  android:layout_height="..."
  [...]
</com.my.package.TextView_Roboto>

Of course you can create a TextView layout. One for Pre HC, one for HC and above(You'll have to make use of the layout and layout-v11 folders). Now you can use the <include> tag to include the TextView in your Layout. You just have to do this use this then:

if (android.os.Build.VERSION.SDK_INT >= 11){
    TextView txt = (TextView) findViewById(R.id.myTxtView);
}
else{
    TextView_Roboto txt = (TextView_Roboto) findViewById(R.id.myTxtView);
}

Edit:

You can use Roboto natively from Android 4.1+ like this:

android:fontFamily="sans-serif"           // roboto regular
android:fontFamily="sans-serif-light"     // roboto light
android:fontFamily="sans-serif-condensed" // roboto condensed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...