Eclipse layout preview can't resolve custom attribute, ok in runtime - java

I'm coding a simple class to use SVG resource:
public class SvgImageView extends ImageView {
private int svgResourceId = 0;
public SvgImageView(Context context, AttributeSet attrs) {
super(context, attrs);
parseAttributes(context.obtainStyledAttributes(attrs, R.styleable.SvgImageView));
}
private void parseAttributes(TypedArray a) {
this.svgResourceId = a.getResourceId(R.styleable.SvgImageView_svg, 0);
a.recycle();
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
// set correct layer type
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
// set drawable
if (svgResourceId != 0)
setImageDrawable(SvgCache.getSvgPictureDrawable(getContext().getResources(), svgResourceId));
}
}
in the activity XML simply I use it:
<myapp.framework.widget.SvgImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
custom:svg="#raw/lighting" />
Everything works fine in runtime but in editor mode, when opening the Graphical Layout panel, when parsing attributes:
this.svgResourceId = a.getResourceId(R.styleable.SvgImageView_svg, 0);
this.svgResourceId is 0, so I think it can't obtain the resource id. Why?

It may be the same situation as I had recently. To sum it up, it's because the IDE (Eclipse) processes the code with a different output method, resulting in the different display.
Here's a link to the question I had asked, hope it helps. Clearing Screen in C++/XCode

Related

Unable to access Camera in dynamically created Webview

I am trying to access camera through web application. If I create a WebView in XML, it is working fine. But the same doesn't work if I try to create the WebView dynamically. A blank section is coming[ Image attached below]. The Camera Streams are unable to update the view.
This is the WebView Class File
public class PageView extends WebView {
public PageView(Context context) {
super(context);
init();
}
public PageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public PageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public void init() {
setWebChromeClient(new CustomizedWebChromeClient());
setWebViewClient(new WebViewClient());
//File access
getSettings().setAllowFileAccessFromFileURLs(true);
getSettings().setAllowFileAccess(true);
getSettings().setAllowContentAccess(true);
getSettings().setAllowUniversalAccessFromFileURLs(true);
//Video playbacks
getSettings().setMediaPlaybackRequiresUserGesture(false);
getSettings().setJavaScriptEnabled(true);
getSettings().setDomStorageEnabled(true);
getSettings().setAppCacheEnabled(true);
setupHardwareAcceleration();
setWebContentsDebuggingEnabled(true);
}
class CustomizedWebChromeClient extends android.webkit.WebChromeClient
{
#Override
public void onPermissionRequest(PermissionRequest request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
request.grant(request.getResources());
}
}
}
#TargetApi(11)
private void setupHardwareAcceleration() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (isHardwareAccelerated()) {
setLayerType(View.LAYER_TYPE_NONE, null);
} else {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
}
}}
This is the MainActivity Class
private WebView webView = null;
private String url = "https://www.onlinemictest.com/webcam-test/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addWebViewToActivity();
}
public void addWebViewToActivity() {
LinearLayout ll = (LinearLayout) findViewById(R.id.linearlayout);
WebView web = new PageView(this);
web.loadUrl("https://www.onlinemictest.com/webcam-test/");
ll.addView(web);
}
This is the result of the above code.
Note: In some websites which tests the webcam, the results of the tests are coming as normal. All the details of my webcam( Android Camera) is also coming as normal. We were even be able to take photos. But the stream from camera to view is not coming. Only as blank. Also, the number in the blank area represents the number of frames.
Found the issue.
I thought that the issue is due to the difference between creating WebView dynamically vs from XML. But the real reason for the issue is, When we create a customized WebView like
public CustomizedWebView extends WebView
and a normal object of Webview like
Webview webview = new Webview(context);
The difference between both of them is the Layer Type. Layer Type is set as "LAYER_TYPE_NONE" for webview. Because of this, I was getting blank screen.

Typeface custom font doesn't work

Typeface always shows default font.
My fonts are stored in the assets/fonts. And I have tried to use other fonts, and to re-encode fonts. Also PixlUI library didn't solve the problem.
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
Typeface typeface = Typeface.createFromAsset(getAssets(),"fonts/OldEnglishFive.ttf");
button.setTypeface(typeface);
}
activity_main.xml
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="220dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:onClick="doSomething"
android:text="TEXT" />
If you haven't already tried using a font previously. I would suggest deleting your assets folder, creating a new assets folder inside your res folder and then move it back to where it was previously. Sometimes Android Studio doesn't accept the assets folder that gets built.
as shown here Runtime Exception: Font not found for every font i've tried - Android
also, I would reccomend creating a class that extends Button so that it'll automatically set your font for that widget if you assign the right XML to the button.
An example would be:
public class CustomFontButton extends Button {
AttributeSet attr;
public CustomFontButton(Context context) {
super(context);
setCustomFont(context, attr);
}
public CustomFontButton(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context, attrs);
}
public CustomFontButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setCustomFont(context, attrs);
}
private void setCustomFont(Context ctx, AttributeSet attrs) {
String customFont = null;
TypedArray a = null;
if (attrs != null) {
a = ctx.obtainStyledAttributes(attrs, R.styleable.CustomFontButton);
customFont = a.getString(R.styleable.CustomFontButton_customFont);
}
if (customFont == null) customFont = "fonts/OldEnglishFive.ttf";
setCustomFont(ctx, customFont);
if (a != null) {
a.recycle();
}
}
public boolean setCustomFont(Context ctx, String asset) {
Typeface tf = null;
try {
tf = Typeface.createFromAsset(ctx.getAssets(), asset);
} catch (Exception e) {
Log.e("textView", "Could not get typeface", e);
return false;
}
setTypeface(tf);
return true;
}
}
and then in your xml you would only need to change
<yourpackagename.CustomFontButton
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="220dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:onClick="doSomething"
android:text="TEXT" />
create an attrs.xml inside your values folder.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomFontButton">
<attr name="customFont" format="string"/>
</declare-styleable>
</resources >
This would save you having to do setTypeFace everytime you would like a custom font on a button (or most other widgets, the same logic can be applied)
Instead of directly setting Typeface using setTypeface method, try below code snippet:
protected void onCreate(Bundle savedInstanceState) {
... //do whatever you want
Button button = (Button) findViewById(R.id.button);
Typeface typeface = Typeface.createFromAsset(getAssets(),"fonts/OldEnglishFive.ttf");
button.setText(changeFontStyle("your text", typeface));
}
// custom function for changing the font style of text
public Spannable changeFontStyle(String finalString, Typeface typeface){
spannable = new SpannableString(finalString);
spannable.setSpan(new CustomTypefaceSpan("", typeface), 0, finalString.length(), 0);
return spannable;
}
Le me know if face any problem.
A good option would be to double check your folder, font and font directory name spellings. A good idea would be to show any errors that would've been printed and post them for us to understand the problem a little better. If you could also post the font name and double check if they are the same, and make sure that your assets are in the right location hope I helped.

Using custom font in android TextView using xml

I have added a custom font file to my assets/fonts folder. How do I use it from my XML?
I can use it from code as follows:
TextView text = (TextView) findViewById(R.id.textview03);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/Molot.otf");
text.setTypeface(tf);
Can't I do it from XML using an android:typeface="/fonts/Molot.otf" attribute?
Short answer: No. Android doesn't have built-in support for applying custom fonts to text widgets through XML.
However, there's a workaround that's not terribly difficult to implement.
First
You'll need to define your own stylable. In your /res/values folder, open/create the attrs.xml file and add a declare-styleable object like so:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="FontText">
<attr name="typefaceAsset" format="string"/>
</declare-styleable>
</resources>
Second
Assuming you want to use this widget often, you should set up a simple cache for the loaded Typeface objects, since loading them from memory on the fly can take time. Something like:
public class FontManager {
private static FontManager instance;
private AssetManager mgr;
private Map<String, Typeface> fonts;
private FontManager(AssetManager _mgr) {
mgr = _mgr;
fonts = new HashMap<String, Typeface>();
}
public static void init(AssetManager mgr) {
instance = new FontManager(mgr);
}
public static FontManager getInstance() {
if (instance == null) {
// App.getContext() is just one way to get a Context here
// getContext() is just a method in an Application subclass
// that returns the application context
AssetManager assetManager = App.getContext().getAssets();
init(assetManager);
}
return instance;
}
public Typeface getFont(String asset) {
if (fonts.containsKey(asset))
return fonts.get(asset);
Typeface font = null;
try {
font = Typeface.createFromAsset(mgr, asset);
fonts.put(asset, font);
} catch (Exception e) {
}
if (font == null) {
try {
String fixedAsset = fixAssetFilename(asset);
font = Typeface.createFromAsset(mgr, fixedAsset);
fonts.put(asset, font);
fonts.put(fixedAsset, font);
} catch (Exception e) {
}
}
return font;
}
private String fixAssetFilename(String asset) {
// Empty font filename?
// Just return it. We can't help.
if (TextUtils.isEmpty(asset))
return asset;
// Make sure that the font ends in '.ttf' or '.ttc'
if ((!asset.endsWith(".ttf")) && (!asset.endsWith(".ttc")))
asset = String.format("%s.ttf", asset);
return asset;
}
}
This one will allow you to use .ttc file extensions, but it's untested.
Third
Create a new class that subclasses TextView. This particular example takes into account the defined XML typeface (bold, italic, etc.) and apply it to the font (assuming you're using a .ttc file).
/**
* TextView subclass which allows the user to define a truetype font file to use as the view's typeface.
*/
public class FontText extends TextView {
public FontText(Context context) {
this(context, null);
}
public FontText(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FontText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if (isInEditMode())
return;
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.FontText);
if (ta != null) {
String fontAsset = ta.getString(R.styleable.FontText_typefaceAsset);
if (!TextUtils.isEmpty(fontAsset)) {
Typeface tf = FontManager.getInstance().getFont(fontAsset);
int style = Typeface.NORMAL;
float size = getTextSize();
if (getTypeface() != null)
style = getTypeface().getStyle();
if (tf != null)
setTypeface(tf, style);
else
Log.d("FontText", String.format("Could not create a font from asset: %s", fontAsset));
}
}
}
}
Finally
Replace the instances of TextView in your XML with the fully qualified class name. Declare your custom namespace just like you would the Android namespace. Note that the "typefaceAsset" should point to a .ttf or .ttc file contained in your /assets directory.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.FontText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a custom font text"
custom:typefaceAsset="fonts/AvenirNext-Regular.ttf"/>
</RelativeLayout>
Here is example code that does this. I have the font defined in a static final variable and the font file is in the assets directory.
public class TextViewWithFont extends TextView {
public TextViewWithFont(Context context, AttributeSet attrs) {
super(context, attrs);
this.setTypeface(MainActivity.typeface);
}
public TextViewWithFont(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setTypeface(MainActivity.typeface);
}
public TextViewWithFont(Context context) {
super(context);
this.setTypeface(MainActivity.typeface);
}
}
Create your customed TextView belong to the font you want to use. In this class, I use a static mTypeface field to cache the Typeface (for better performance)
public class HeliVnTextView extends TextView {
/*
* Caches typefaces based on their file path and name, so that they don't have to be created every time when they are referenced.
*/
private static Typeface mTypeface;
public HeliVnTextView(final Context context) {
this(context, null);
}
public HeliVnTextView(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
public HeliVnTextView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
if (mTypeface == null) {
mTypeface = Typeface.createFromAsset(context.getAssets(), "HelveticaiDesignVnLt.ttf");
}
setTypeface(mTypeface);
}
}
In xml file:
<java.example.HeliVnTextView
android:id="#+id/textView1"
android:layout_width="0dp"
... />
In java class:
HeliVnTextView title = new HeliVnTextView(getActivity());
title.setText(issue.getName());
Activity implements LayoutInflater.Factory2 that provides callbacks on each created View.
It's possible to style the TextView with custom font Family attribute, load the typefaces on demand and call setTypeface on instantiated text views automatically.
Unfortunately due to the architectural relationship of Inflater instances relative to Activities and Windows the simplest approach to use custom fonts in android is to cache loaded fonts on the Application level.
The sample code base is here:
https://github.com/leok7v/android-textview-custom-fonts
<style name="Baroque" parent="#android:style/TextAppearance.Medium">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">#F2BAD0</item>
<item name="android:textSize">14pt</item>
<item name="fontFamily">baroque_script</item>
</style>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/custom.fonts"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
style="#style/Baroque"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/sample_text"
/>
results in
Not a good idea to use custom fonts in xml due to this fact
that is, you have to do it programmatically to avoid the memory leak!
UPDATE: https://github.com/chrisjenx/Calligraphy appears to be a
superior solution to this.
Maybe you can use reflection to inject/hack your font into the static list of available fonts when your application is created? I am interested in feedback from others if this is a really, really bad idea or if this is a great solution — it seems it is going to be one of those extremes...
I was able to inject my custom typeface into the list of system typefaces with my own font family name, then specifying that custom font family name ("brush-script") as the value of android:FontFamily on a standard TextView worked on my LG G4 running Android 6.0.
public class MyApplication extends android.app.Application
{
#Override
public void onCreate()
{
super.onCreate();
Typeface font = Typeface.createFromAsset(this.getResources().getAssets(),"fonts/brush-script.ttf");
injectTypeface("brush-script", font);
}
private boolean injectTypeface(String fontFamily, Typeface typeface)
{
try
{
Field field = Typeface.class.getDeclaredField("sSystemFontMap");
field.setAccessible(true);
Object fieldValue = field.get(null);
Map<String, Typeface> map = (Map<String, Typeface>) fieldValue;
map.put(fontFamily, typeface);
return true;
}
catch (Exception e)
{
Log.e("Font-Injection", "Failed to inject typeface.", e);
}
return false;
}
}
In my layout
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fancy Text"
android:fontFamily="brush-script"/>
Create a fonts folder in assets and add all your required font's there.
public class CustomTextView extends TextView {
private static final String TAG = "TextView";
public CustomTextView(Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context, attrs);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setCustomFont(context, attrs);
}
private void setCustomFont(Context ctx, AttributeSet attrs) {
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.CustomTextView);
String customFont = a.getString(R.styleable.CustomTextView_customFont);
setCustomFont(ctx, customFont);
a.recycle();
}
public boolean setCustomFont(Context ctx, String fontName) {
Typeface typeface = null;
try {
if(fontName == null){
fontName = Constants.DEFAULT_FONT_NAME;
}
typeface = Typeface.createFromAsset(ctx.getAssets(), "fonts/" + fontName);
} catch (Exception e) {
Log.e(TAG, "Unable to load typeface: "+e.getMessage());
return false;
}
setTypeface(typeface);
return true;
}
}
and add a declarable in attrs.xml
<declare-styleable name="CustomTextView">
<attr name="customFont" format="string"/>
</declare-styleable>
and then add your customFont like
app:customFont="arial.ttf"
I know this is an old question, but i've found a much easier solution.
First declare your TextView in xml as usual.
Put your font (TTF or TTC) in the asset folder
app\src\main\assets\
Then just set the typeface for your text view in your onCreate method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name);
TextView textView = findViewById(R.id.my_textView);
Typeface typeface = Typeface.createFromAsset(getAssets(), "fontName.ttf");
textView.setTypeface(typeface);
}
Done.
The best solution is to use (finally) introduced by Google a native custom font feature in XML. But you have to target API 26. It supports API 16+
https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml
instead of xmlns:custom="schemas.android.com/tools"; you should use: xmlns:custom="schemas.android.com/apk/res-auto"; in order to use styleable attributes.
I made this change and it is working now.
the latest update now that you can set the font in XML without any other classes added like:
android:fontFamily="#font_folder/font_file"

Display Animated GIF

I want to display animated GIF images in my aplication.
As I found out the hard way Android doesn't support animated GIF natively.
However it can display animations using AnimationDrawable:
Develop > Guides > Images & Graphics > Drawables Overview
The example uses animation saved as frames in application resources but what I need is to display animated gif directly.
My plan is to break animated GIF to frames and add each frame as drawable to AnimationDrawable.
Does anyone know how to extract frames from animated GIF and convert each of them into Drawable?
Android actually can decode and display animated GIFs, using android.graphics.Movie class.
This is not too much documented, but is in SDK Reference. Moreover, it is used in Samples in ApiDemos in BitmapDecode example with some animated flag.
UPDATE:
Use glide:
dependencies {
implementation 'com.github.bumptech.glide:glide:4.9.0'
}
usage:
Glide.with(context).load(GIF_URI).into(new DrawableImageViewTarget(IMAGE_VIEW));
see docs
also put (main/assets/htmls/name.gif) [with this html adjust to the size]
<html style="margin: 0;">
<body style="margin: 0;">
<img src="name.gif" style="width: 100%; height: 100%" />
</body>
</html>
declare in your Xml for example like this (main/res/layout/name.xml): [you define the size, for example]
<WebView
android:layout_width="70dp"
android:layout_height="70dp"
android:id="#+id/webView"
android:layout_gravity="center_horizontal" />
in your Activity put the next code inside of onCreate
web = (WebView) findViewById(R.id.webView);
web.setBackgroundColor(Color.TRANSPARENT); //for gif without background
web.loadUrl("file:///android_asset/htmls/name.html");
if you want load dynamically you have to load the webview with data:
// or "[path]/name.gif" (e.g: file:///android_asset/name.gif for resources in asset folder), and in loadDataWithBaseURL(), you don't need to set base URL, on the other hand, it's similar to loadData() method.
String gifName = "name.gif";
String yourData = "<html style=\"margin: 0;\">\n" +
" <body style=\"margin: 0;\">\n" +
" <img src=" + gifName + " style=\"width: 100%; height: 100%\" />\n" +
" </body>\n" +
" </html>";
// Important to add this attribute to webView to get resource from outside.
webView.getSettings().setAllowFileAccess(true);
// Notice: should use loadDataWithBaseURL. BaseUrl could be the base url such as the path to asset folder, or SDCard or any other path, where your images or the other media resides related to your html
webView.loadDataWithBaseURL("file:///android_asset/", yourData, "text/html", "utf-8", null);
// Or if you want to load image from SD card or where else, here is the idea.
String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
webView.loadDataWithBaseURL(base + '/', yourData, "text/html", "utf-8", null);
suggestion: is better load gif with static images for more information check https://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html
That's it, I hope you help.
Currently we can use Glide https://github.com/bumptech/glide
I solved the problem by splitting gif animations into frames before saving it to phone, so I would not have to deal with it in Android.
Then I download every frame onto phone, create Drawable from it and then create AnimationDrawable - very similar to example from my question
i found a very easy way, with a nice and simple working example here
display animated widget
Before getting it working there are some chages to do do in the code
IN THE FOLLOWING
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceStated);
setContentView(new MYGIFView());
}
}
just replace
setContentView(new MYGIFView());
in
setContentView(new MYGIFView(this));
AND IN
public GIFView(Context context) {
super(context);
Provide your own gif animation file
is = context.getResources().openRawResource(R.drawable.earth);
movie = Movie.decodeStream(is);
}
REPLACE THE FIRST LINE IN
public MYGIFView(Context context) {
according to the name of the class...
after done this little changes it should work as for me...
hope this help
Glide 4.6
1. To Load gif
GlideApp.with(context)
.load(R.raw.gif) // or url
.into(imageview);
2. To get the file object
GlideApp.with(context)
.asGif()
.load(R.raw.gif) //or url
.into(new SimpleTarget<GifDrawable>() {
#Override
public void onResourceReady(#NonNull GifDrawable resource, #Nullable Transition<? super GifDrawable> transition) {
resource.start();
//resource.setLoopCount(1);
imageView.setImageDrawable(resource);
}
});
Ways to show animated GIF on Android:
Movie class. As mentioned above, it's fairly buggy.
WebView. It's very simple to use and usually works. But sometimes it starts to misbehave, and it's always on some obscure devices you don't have. Plus, you can’t use multiple instances in any kind of list views, because it does things to your memory. Still, you might consider it as a primary approach.
Custom code to decode gifs into bitmaps and show them as Drawable or ImageView. I'll mention two libraries:
https://github.com/koral--/android-gif-drawable - decoder is implemented in C, so it's very efficient.
https://code.google.com/p/giffiledecoder - decoder is implemented in Java, so it's easier to work with. Still reasonably efficient, even with large files.
You'll also find many libraries based on GifDecoder class. That's also a Java-based decoder, but it works by loading the entire file into memory, so it's only applicable to small files.
I had a really hard time to have animated gif working in Android. I only had following two working:
WebView
Ion
WebView works OK and really easy, but the problem is it makes the view loads slower and the app would be unresponsive for a second or so. I did not like that. So I have tried different approaches (DID NOT WORK):
ImageViewEx is deprecated!
picasso did not load animated gif
android-gif-drawable looks great, but it caused some wired NDK issues in my project. It caused my local NDK library stop working, and I was not able to fix it
I had some back and forth with Ion; Finally, I have it working, and it is really fast :-)
Ion.with(imgView)
.error(R.drawable.default_image)
.animateGif(AnimateGifMode.ANIMATE)
.load("file:///android_asset/animated.gif");
Glide
Image Loader Library for Android, recommended by Google.
Glide is quite similar to Picasso but this is much faster than Picasso.
Glide consumes less memory than Picasso.
What that Glide has but Picasso doesn't
An ability to load GIF Animation to a simple ImageView might be the most interesting feature of Glide. And yes, you can't do that with Picasso.
Some important links-
https://github.com/bumptech/glide
http://inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/en
Use ImageViewEx, a library that makes using a gif as easy as using an ImageView.
Try this, bellow code display gif file in progressbar
loading_activity.xml(in Layout folder)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff" >
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:indeterminate="true"
android:indeterminateDrawable="#drawable/custom_loading"
android:visibility="gone" />
</RelativeLayout>
custom_loading.xml(in drawable folder)
here i put black_gif.gif(in drawable folder), you can put your own gif here
<?xml version="1.0" encoding="utf-8"?>
<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="#drawable/black_gif"
android:pivotX="50%"
android:pivotY="50%" />
LoadingActivity.java(in res folder)
public class LoadingActivity extends Activity {
ProgressBar bar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading);
bar = (ProgressBar) findViewById(R.id.progressBar);
bar.setVisibility(View.VISIBLE);
}
}
Nobody has mentioned the Ion or Glide library. they work very well.
It's easier to handle compared to a WebView.
I have had success with the solution proposed within this article, a class called GifMovieView, which renders a View which can then be displayed or added to a specific ViewGroup. Check out the other methods presented in parts 2 and 3 of the specified article.
The only drawback to this method is that the antialiasing on the movie is not that good (must be a side-effect of using the "shady" Android Movie Class). You are then better off setting the background to a solid color within your animated GIF.
Some thoughts on the BitmapDecode example... Basically it uses the ancient, but rather featureless Movie class from android.graphics.
On recent API versions you need to turn off hardware acceleration, as described here. It was segfaulting for me otherwise.
<activity
android:hardwareAccelerated="false"
android:name="foo.GifActivity"
android:label="The state of computer animation 2014">
</activity>
Here is the BitmapDecode example shortened with only the GIF part. You have to make your own Widget (View) and draw it by yourself. Not quite as powerful as an ImageView.
import android.app.Activity;
import android.content.Context;
import android.graphics.*;
import android.os.*;
import android.view.View;
public class GifActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GifView(this));
}
static class GifView extends View {
Movie movie;
GifView(Context context) {
super(context);
movie = Movie.decodeStream(
context.getResources().openRawResource(
R.drawable.some_gif));
}
#Override
protected void onDraw(Canvas canvas) {
if (movie != null) {
movie.setTime(
(int) SystemClock.uptimeMillis() % movie.duration());
movie.draw(canvas, 0, 0);
invalidate();
}
}
}
}
2 other methods, one with ImageView another with WebView can be found in this fine tutorial. The ImageView method uses the Apache licensed android-gifview from Google Code.
#PointerNull gave good solution, but it is not perfect. It doesn't work on some devices with big files and show buggy Gif animation with delta frames on pre ICS version.
I found solution without this bugs. It is library with native decoding to drawable: koral's android-gif-drawable.
For only android API (Android Pie)28 and + use AnimatedImageDrawable as
// ImageView from layout
val ima : ImageView = findViewById(R.id.img_gif)
// create AnimatedDrawable
val decodedAnimation = ImageDecoder.decodeDrawable(
// create ImageDecoder.Source object
ImageDecoder.createSource(resources, R.drawable.tenor))
// set the drawble as image source of ImageView
ima.setImageDrawable(decodedAnimation)
// play the animation
(decodedAnimation as? AnimatedImageDrawable)?.start()
XML code, add a ImageView
<ImageView
android:id="#+id/img_gif"
android:background="#drawable/ic_launcher_background" <!--Default background-->
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_width="200dp"
android:layout_height="200dp" />
AnimatedImageDrawable is a child of Drawable and created by ImageDecoder.decodeDrawable
ImageDecoder.decodeDrawable which further required the instance of ImageDecoder.Source created by ImageDecoder.createSource.
ImageDecoder.createSource can only take source as a name, ByteBuffer, File, resourceId, URI, ContentResolver to create source object and uses it to create AnimatedImageDrawable as Drawable (polymorphic call)
static ImageDecoder.Source createSource(AssetManager assets, String fileName)
static ImageDecoder.Source createSource(ByteBuffer buffer)
static ImageDecoder.Source createSource(File file)
static ImageDecoder.Source createSource(Resources res, int resId)
static ImageDecoder.Source createSource(ContentResolver cr, Uri uri)
Note: You can also create Bitmap using ImageDecoder#decodeBitmap.
Output:
AnimatedDrawable also supports resizing, frame and color manipulation
Put it into a WebView, it has to be able to display it correctly, since the default browser supports gif files. (Froyo+, if i am not mistaken)
There are two options to load animated gifs into our Android apps
1)Using Glide to load the gif into an ImageView.
String urlGif = "https://cdn.dribbble.com/users/263558/screenshots/1337078/dvsd.gif";
//add Glide implementation into the build.gradle file.
ImageView imageView = (ImageView)findViewById(R.id.imageView);
Uri uri = Uri.parse(urlGif);
Glide.with(getApplicationContext()).load(uri).into(imageView);
2) Using an html to load the gif into a WebView
Create the html with the address to the .gif file:
<html style="margin: 0;">
<body style="margin: 0;">
<img src="https://..../myimage.gif" style="width: 100%; height: 100%" />
</body>
</html>
store this file into the assets directory:
The load this html into the WebView of your application:
WebView webView = (WebView)findViewById(R.id.webView);
webView = (WebView) findViewById(R.id.webView);
webView.loadUrl("file:///android_asset/html/webpage_gif.html");
Heres is a complete example of this two options.
I think the better library to handle gif files is this one: by koral
Used it and i'm successful and this library is dedicated to GIF'S; but where as the picasso and glide are general purpose image framework; so i think the developers of this library have entirely concentrated on gif files
Use fresco. Here's how to do it:
http://frescolib.org/docs/animations.html
Here's the repo with the sample:
https://github.com/facebook/fresco/tree/master/samples/animation
Beware fresco does not support wrap content!
Just wanted to add that the Movie class is now deprecated.
This class was deprecated in API level P.
It is recommended to use this
AnimatedImageDrawable
Drawable for drawing animated images (like GIF).
Similar to what #Leonti said, but with a little more depth:
What I did to solve the same problem was open up GIMP, hide all layers except for one, export it as its own image, and then hide that layer and unhide the next one, etc., until I had individual resource files for each one. Then I could use them as frames in the AnimationDrawable XML file.
Something I did for showing gifs in apps. I extended ImageView so people can use its attributes freely. It can show gifs from url or from the assets directory.
The library also makes it easy for extending classes to inherit from it and extend it to support different methods to initialize the gif.
https://github.com/Gavras/GIFView
There's a little guide on the github page.
It was also published on Android Arsenal:
https://android-arsenal.com/details/1/4947
Use example:
From XML:
<com.whygraphics.gifview.gif.GIFView xmlns:gif_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_activity_gif_vie"
android:layout_width="200dp"
android:layout_height="200dp"
android:scaleType="center"
gif_view:gif_src="url:http://pop.h-cdn.co/assets/16/33/480x264/gallery-1471381857-gif-season-2.gif" />
In the activity:
GIFView mGifView = (GIFView) findViewById(R.id.main_activity_gif_vie);
mGifView.setOnSettingGifListener(new GIFView.OnSettingGifListener() {
#Override
public void onSuccess(GIFView view, Exception e) {
Toast.makeText(MainActivity.this, "onSuccess()", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(GIFView view, Exception e) {
}
});
Setting the gif programmatically:
mGifView.setGifResource("asset:gif1");
Easiest way - Can be consider the below code
We can take advantage of Imageview setImageResource , refer below code for the same.
The below code can be used to show the image like gif incase if you have the multiple split image of gif. Just split the gif into individual png from a online tool and put image in the drawable like the below order
image_1.png, image_2.png, etc.
Have the handler to change the image dynamically.
int imagePosition = 1;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
updateImage();
}
};
public void updateImage() {
appInstance.runOnUiThread(new Runnable() {
#Override
public void run() {
int resId = getResources().getIdentifier("image_" + imagePosition, "drawable", appInstance.getPackageName());
gifImageViewDummy.setImageResource(resId);
imagePosition++;
//Consider you have 30 image for the anim
if (imagePosition == 30) {
//this make animation play only once
handler.removeCallbacks(runnable);
} else {
//You can define your own time based on the animation
handler.postDelayed(runnable, 50);
}
//to make animation to continue use below code and remove above if else
// if (imagePosition == 30)
//imagePosition = 1;
// handler.postDelayed(runnable, 50);
//
}
});
}
The easy way to display animated GIF directly from URL to your app layout is to use WebView class.
Step 1:
In your layout XML
<WebView
android:id="#+id/webView"
android:layout_width="50dp"
android:layout_height="50dp"
/>
Step 2: In your Activity
WebView wb;
wb = (WebView) findViewById(R.id.webView);
wb.loadUrl("https://.......);
Step 3: In your Manifest.XML make Internet permission
<uses-permission android:name="android.permission.INTERNET" />
Step 4: In case you want to make your GIF background transparent and make GIF fit to your Layout
wb.setBackgroundColor(Color.TRANSPARENT);
wb.getSettings().setLoadWithOverviewMode(true);
wb.getSettings().setUseWideViewPort(true);
If you want to use Glide for loading gif:
Glide.with(this)
.asGif()
.load(R.raw.onboarding_layers) //Your gif resource
.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
.listener(new RequestListener<GifDrawable>() {
#Override
public boolean onLoadFailed(#Nullable #org.jetbrains.annotations.Nullable GlideException e, Object model, Target<GifDrawable> target, boolean isFirstResource) {
return false;
}
#Override
public boolean onResourceReady(GifDrawable resource, Object model, Target<GifDrawable> target, DataSource dataSource, boolean isFirstResource) {
resource.setLoopCount(1);
return false;
}
})
.into((ImageView) view.findViewById(R.id.layer_icons));
To save resources there is glide library for.
Have no idea why to use anything else, especialy webview to show image only.
Glide is perfect and easy library that prepares animated drawable from gif and put it directly to imageview.
The logic of gifdrawable handle animation itself.
Gif have lzw ziped raw rgb data of an animation inside.
There is no reason for complicated usage of webview and manage more files to show just a gif file in app.
First of all the Android browser should support Animated GIFs. If it doesn't then it's a bug! Have a look at the issue trackers.
If you're displaying these animated GIFs outside of a browser it might be a different story. To do what you're asking would require external library that supports the decoding of Animated GIFs.
The first port of call would be to look at Java2D or JAI (Java Advanced Imaging) API, although I would be very surprised if Android Dalvik would support those libraries in your App.
public class Test extends GraphicsActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleView(this));
}
private static class SampleView extends View {
private Bitmap mBitmap;
private Bitmap mBitmap2;
private Bitmap mBitmap3;
private Bitmap mBitmap4;
private Drawable mDrawable;
private Movie mMovie;
private long mMovieStart;
// Set to false to use decodeByteArray
private static final boolean DECODE_STREAM = true;
private static byte[] streamToBytes(InputStream is) {
ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int len;
try {
while ((len = is.read(buffer)) >= 0) {
os.write(buffer, 0, len);
}
} catch (java.io.IOException e) {
}
return os.toByteArray();
}
public SampleView(Context context) {
super(context);
setFocusable(true);
java.io.InputStream is;
is = context.getResources().openRawResource(R.drawable.icon);
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bm;
opts.inJustDecodeBounds = true;
bm = BitmapFactory.decodeStream(is, null, opts);
// now opts.outWidth and opts.outHeight are the dimension of the
// bitmap, even though bm is null
opts.inJustDecodeBounds = false; // this will request the bm
opts.inSampleSize = 4; // scaled down by 4
bm = BitmapFactory.decodeStream(is, null, opts);
mBitmap = bm;
// decode an image with transparency
is = context.getResources().openRawResource(R.drawable.icon);
mBitmap2 = BitmapFactory.decodeStream(is);
// create a deep copy of it using getPixels() into different configs
int w = mBitmap2.getWidth();
int h = mBitmap2.getHeight();
int[] pixels = new int[w * h];
mBitmap2.getPixels(pixels, 0, w, 0, 0, w, h);
mBitmap3 = Bitmap.createBitmap(pixels, 0, w, w, h,
Bitmap.Config.ARGB_8888);
mBitmap4 = Bitmap.createBitmap(pixels, 0, w, w, h,
Bitmap.Config.ARGB_4444);
mDrawable = context.getResources().getDrawable(R.drawable.icon);
mDrawable.setBounds(150, 20, 300, 100);
is = context.getResources().openRawResource(R.drawable.animated_gif);
if (DECODE_STREAM) {
mMovie = Movie.decodeStream(is);
} else {
byte[] array = streamToBytes(is);
mMovie = Movie.decodeByteArray(array, 0, array.length);
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(0xFFCCCCCC);
Paint p = new Paint();
p.setAntiAlias(true);
canvas.drawBitmap(mBitmap, 10, 10, null);
canvas.drawBitmap(mBitmap2, 10, 170, null);
canvas.drawBitmap(mBitmap3, 110, 170, null);
canvas.drawBitmap(mBitmap4, 210, 170, null);
mDrawable.draw(canvas);
long now = android.os.SystemClock.uptimeMillis();
if (mMovieStart == 0) { // first time
mMovieStart = now;
}
if (mMovie != null) {
int dur = mMovie.duration();
if (dur == 0) {
dur = 1000;
}
int relTime = (int) ((now - mMovieStart) % dur);
mMovie.setTime(relTime);
mMovie.draw(canvas, getWidth() - mMovie.width(), getHeight()
- mMovie.height());
invalidate();
}
}
}
}
class GraphicsActivity extends Activity {
// set to true to test Picture
private static final boolean TEST_PICTURE = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void setContentView(View view) {
if (TEST_PICTURE) {
ViewGroup vg = new PictureLayout(this);
vg.addView(view);
view = vg;
}
super.setContentView(view);
}
}
class PictureLayout extends ViewGroup {
private final Picture mPicture = new Picture();
public PictureLayout(Context context) {
super(context);
}
public PictureLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void addView(View child) {
if (getChildCount() > 1) {
throw new IllegalStateException(
"PictureLayout can host only one direct child");
}
super.addView(child);
}
#Override
public void addView(View child, int index) {
if (getChildCount() > 1) {
throw new IllegalStateException(
"PictureLayout can host only one direct child");
}
super.addView(child, index);
}
#Override
public void addView(View child, LayoutParams params) {
if (getChildCount() > 1) {
throw new IllegalStateException(
"PictureLayout can host only one direct child");
}
super.addView(child, params);
}
#Override
public void addView(View child, int index, LayoutParams params) {
if (getChildCount() > 1) {
throw new IllegalStateException(
"PictureLayout can host only one direct child");
}
super.addView(child, index, params);
}
#Override
protected LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int count = getChildCount();
int maxHeight = 0;
int maxWidth = 0;
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
measureChild(child, widthMeasureSpec, heightMeasureSpec);
}
}
maxWidth += getPaddingLeft() + getPaddingRight();
maxHeight += getPaddingTop() + getPaddingBottom();
Drawable drawable = getBackground();
if (drawable != null) {
maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
}
setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec),
resolveSize(maxHeight, heightMeasureSpec));
}
private void drawPict(Canvas canvas, int x, int y, int w, int h, float sx,
float sy) {
canvas.save();
canvas.translate(x, y);
canvas.clipRect(0, 0, w, h);
canvas.scale(0.5f, 0.5f);
canvas.scale(sx, sy, w, h);
canvas.drawPicture(mPicture);
canvas.restore();
}
#Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(mPicture.beginRecording(getWidth(), getHeight()));
mPicture.endRecording();
int x = getWidth() / 2;
int y = getHeight() / 2;
if (false) {
canvas.drawPicture(mPicture);
} else {
drawPict(canvas, 0, 0, x, y, 1, 1);
drawPict(canvas, x, 0, x, y, -1, 1);
drawPict(canvas, 0, y, x, y, 1, -1);
drawPict(canvas, x, y, x, y, -1, -1);
}
}
#Override
public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
location[0] = getLeft();
location[1] = getTop();
dirty.set(0, 0, getWidth(), getHeight());
return getParent();
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int count = super.getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final int childLeft = getPaddingLeft();
final int childTop = getPaddingTop();
child.layout(childLeft, childTop,
childLeft + child.getMeasuredWidth(),
childTop + child.getMeasuredHeight());
}
}
}
}

Custom fonts and XML layouts (Android)

I'm trying to define a GUI layout using XML files in Android. As far as I can find out, there is no way to specify that your widgets should use a custom font (e.g. one you've placed in assets/font/) in XML files and you can only use the system installed fonts.
I know that, in the Java code, I could change the font of each widget manually using unique IDs. Alternatively, I could iterate over all the widgets in Java to make this change, but this would probably be very slow.
What other options do I have? Is there any better ways to making widgets that have a custom look? I don't particularly want to have to manually change the font for every new widget I add.
You can extend TextView to set custom fonts as I learned here.
TextViewPlus.java:
package com.example;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
public class TextViewPlus extends TextView {
private static final String TAG = "TextView";
public TextViewPlus(Context context) {
super(context);
}
public TextViewPlus(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context, attrs);
}
public TextViewPlus(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setCustomFont(context, attrs);
}
private void setCustomFont(Context ctx, AttributeSet attrs) {
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus);
String customFont = a.getString(R.styleable.TextViewPlus_customFont);
setCustomFont(ctx, customFont);
a.recycle();
}
public boolean setCustomFont(Context ctx, String asset) {
Typeface tf = null;
try {
tf = Typeface.createFromAsset(ctx.getAssets(), asset);
} catch (Exception e) {
Log.e(TAG, "Could not get typeface: "+e.getMessage());
return false;
}
setTypeface(tf);
return true;
}
}
attrs.xml: (in res/values)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TextViewPlus">
<attr name="customFont" format="string"/>
</declare-styleable>
</resources>
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:foo="http://schemas.android.com/apk/res/com.example"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.example.TextViewPlus
android:id="#+id/textViewPlus1"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:text="#string/showingOffTheNewTypeface"
foo:customFont="saxmono.ttf">
</com.example.TextViewPlus>
</LinearLayout>
You would put "saxmono.ttf" in the assets folder.
UPDATE 8/1/13
There are serious memory concerns with this method. See chedabob's comment below.
I'm 3 years late for the party :( However this could be useful for someone who might stumble upon this post.
I've written a library that caches Typefaces and also allow you to specify custom typefaces right from XML. You can find the library here.
Here is how your XML layout would look like, when you use it.
<com.mobsandgeeks.ui.TypefaceTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
geekui:customTypeface="fonts/custom_font.ttf" />
This might be a little late, but you need to create a singleton class that returns the custom typeface to avoid memory leaks.
TypeFace class:
public class OpenSans {
private static OpenSans instance;
private static Typeface typeface;
public static OpenSans getInstance(Context context) {
synchronized (OpenSans.class) {
if (instance == null) {
instance = new OpenSans();
typeface = Typeface.createFromAsset(context.getResources().getAssets(), "open_sans.ttf");
}
return instance;
}
}
public Typeface getTypeFace() {
return typeface;
}
}
Custom TextView:
public class NativelyCustomTextView extends TextView {
public NativelyCustomTextView(Context context) {
super(context);
setTypeface(OpenSans.getInstance(context).getTypeFace());
}
public NativelyCustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setTypeface(OpenSans.getInstance(context).getTypeFace());
}
public NativelyCustomTextView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
setTypeface(OpenSans.getInstance(context).getTypeFace());
}
}
By xml:
<com.yourpackage.views.NativelyCustomTextView
android:id="#+id/natively_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_margin="20dp"
android:text="#string/natively"
android:textSize="30sp" />
Programmatically:
TextView programmaticallyTextView = (TextView)
findViewById(R.id.programmatically_text_view);
programmaticallyTextView.setTypeface(OpenSans.getInstance(this)
.getTypeFace());
Old question, but I sure wish I read this answer here before I started my own search for a good solution. Calligraphy extends the android:fontFamily attribute to add support for custom fonts in your asset folder, like so:
<TextView
android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="fonts/Roboto-Bold.ttf"/>
The only thing you have to do to activate it is attaching it to the Context of the Activity you're using:
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(new CalligraphyContextWrapper(newBase));
}
You can also specify your own custom attribute to replace android:fontFamily
It also works in themes, including the AppTheme.
Using DataBinding :
#BindingAdapter({"bind:font"})
public static void setFont(TextView textView, String fontName){
textView.setTypeface(Typeface.createFromAsset(textView.getContext().getAssets(), "fonts/" + fontName));
}
In XML:
<TextView
app:font="#{`Source-Sans-Pro-Regular.ttf`}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
font file must be in assets/fonts/
If you only have one typeface you would like to add, and want less code to write, you can create a dedicated TextView for your specific font. See code below.
package com.yourpackage;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class FontTextView extends TextView {
public static Typeface FONT_NAME;
public FontTextView(Context context) {
super(context);
if(FONT_NAME == null) FONT_NAME = Typeface.createFromAsset(context.getAssets(), "fonts/FontName.otf");
this.setTypeface(FONT_NAME);
}
public FontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
if(FONT_NAME == null) FONT_NAME = Typeface.createFromAsset(context.getAssets(), "fonts/FontName.otf");
this.setTypeface(FONT_NAME);
}
public FontTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if(FONT_NAME == null) FONT_NAME = Typeface.createFromAsset(context.getAssets(), "fonts/FontName.otf");
this.setTypeface(FONT_NAME);
}
}
In main.xml, you can now add your textView like this:
<com.yourpackage.FontTextView
android:id="#+id/tvTimer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
The best way to do it From Android O preview release is this way
1.)Right-click the res folder and go to New > Android resource directory. The New
Resource Directory window appears.
2.)In the Resource type list, select font, and then click OK.
3.)Add your font files in the font folder.The folder structure below generates R.font.dancing_script, R.font.la_la, and R.font.ba_ba.
4.)Double-click a font file to preview the file's fonts in the editor.
Next we must create a font family
1.)Right-click the font folder and go to New > Font resource file. The New Resource File window appears.
2.)Enter the file name, and then click OK. The new font resource XML opens in the editor.
3.)Enclose each font file, style, and weight attribute in the font tag element. The following XML illustrates adding font-related attributes in the font resource XML:
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
<font
android:fontStyle="normal"
android:fontWeight="400"
android:font="#font/hey_regular" />
<font
android:fontStyle="italic"
android:fontWeight="400"
android:font="#font/hey_bababa" />
</font-family>
Adding fonts to a TextView:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
**android:fontFamily="#font/ba_ba"**/>
As from the documentation
Working With Fonts
all the steps are correct.
Extend TextView and give it a custom attribute or just use the android:tag attribute to pass in a String of what font you want to use. You will need to pick a convention and stick to it such as I will put all of my fonts in the res/assets/fonts/ folder so your TextView class knows where to find them. Then in your constructor you just set the font manually after the super call.
The only way to use custom fonts is through the source code.
Just remember that Android runs on devices with very limited resources and fonts might require a good amount of RAM. The built-in Droid fonts are specially made and, if you note, have many characters and decorations missing.
I might have a simple answer for the question without extending the TextView and implementing a long code.
Code :
TextView tv = (TextView) findViewById(R.id.textview1);
tv.setTypeface(Typeface.createFromAsset(getAssets(), "font.ttf"));
Place the custom font file in assets folder as usual and try this. It works for me.
I just dont understand why peter has given such a huge code for this simple thing or he has given his answer in old version.
Also can be defined in the xml without creating custom classes
style.xml
<style name="ionicons" parent="android:TextAppearance">
<!-- Custom Attr-->
<item name="fontPath">fonts/ionicons.ttf</item>
</style>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/ionicons"
android:text=""/>
</LinearLayout>
A quick note, because I just always forgot where to put the fonts, its that the font must be inside assets and this folder resides in the same level that res and src, in my case its assets/fonts/ionicons.ttf
Updated Added root layout because this method needs xmlns:app="http://schemas.android.com/apk/res-auto" to work
Update 2 Forgot about a library that I've installed before called Calligraphy
Peter's answer is the best, but it can be improved by using the styles.xml from Android to customize your fonts for all textviews in your app.
My code is here
There are two ways to customize fonts :
!!! my custom font in assets/fonts/iran_sans.ttf
Way 1 :
Refrection Typeface.class ||| best way
call FontsOverride.setDefaultFont() in class extends Application, This code will cause all software fonts to be changed, even Toasts fonts
AppController.java
public class AppController extends Application {
#Override
public void onCreate() {
super.onCreate();
//Initial Font
FontsOverride.setDefaultFont(getApplicationContext(), "MONOSPACE", "fonts/iran_sans.ttf");
}
}
FontsOverride.java
public class FontsOverride {
public static void setDefaultFont(Context context, String staticTypefaceFieldName, String fontAssetName) {
final Typeface regular = Typeface.createFromAsset(context.getAssets(), fontAssetName);
replaceFont(staticTypefaceFieldName, regular);
}
private static void replaceFont(String staticTypefaceFieldName, final Typeface newTypeface) {
try {
final Field staticField = Typeface.class.getDeclaredField(staticTypefaceFieldName);
staticField.setAccessible(true);
staticField.set(null, newTypeface);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
Way 2: use setTypeface
for special view just call setTypeface() to change font.
CTextView.java
public class CTextView extends TextView {
public CTextView(Context context) {
super(context);
init(context,null);
}
public CTextView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init(context,attrs);
}
public CTextView(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context,attrs);
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public CTextView(Context context, #Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context,attrs);
}
public void init(Context context, #Nullable AttributeSet attrs) {
if (isInEditMode())
return;
// use setTypeface for change font this view
setTypeface(FontUtils.getTypeface("fonts/iran_sans.ttf"));
}
}
FontUtils.java
public class FontUtils {
private static Hashtable<String, Typeface> fontCache = new Hashtable<>();
public static Typeface getTypeface(String fontName) {
Typeface tf = fontCache.get(fontName);
if (tf == null) {
try {
tf = Typeface.createFromAsset(AppController.getInstance().getApplicationContext().getAssets(), fontName);
} catch (Exception e) {
e.printStackTrace();
return null;
}
fontCache.put(fontName, tf);
}
return tf;
}
}
Here's a tutorial that shows you how to setup a custom font like #peter described: http://responsiveandroid.com/2012/03/15/custom-fonts-in-android-widgets.html
it also has consideration for potential memory leaks ala http://code.google.com/p/android/issues/detail?id=9904 . Also in the tutorial is an example for setting a custom font on a button.
You can make easily custom textview class :-
So what you need to do first, make Custom textview class which extended with AppCompatTextView.
public class CustomTextView extends AppCompatTextView {
private int mFont = FontUtils.FONTS_NORMAL;
boolean fontApplied;
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, context);
}
public CustomTextView(Context context) {
super(context);
init(null, context);
}
protected void init(AttributeSet attrs, Context cxt) {
if (!fontApplied) {
if (attrs != null) {
mFont = attrs.getAttributeIntValue(
"http://schemas.android.com/apk/res-auto", "Lato-Regular.ttf",
-1);
}
Typeface typeface = getTypeface();
int typefaceStyle = Typeface.NORMAL;
if (typeface != null) {
typefaceStyle = typeface.getStyle();
}
if (mFont > FontUtils.FONTS) {
typefaceStyle = mFont;
}
FontUtils.applyFont(this, typefaceStyle);
fontApplied = true;
}
}
}
Now , every time Custom text view call and we will get int value from attribute int fontValue = attrs.getAttributeIntValue("http://schemas.android.com/apk/res-auto","Lato-Regular.ttf",-1).
Or
We can also get getTypeface() from view which we set in our xml (android:textStyle="bold|normal|italic"). So do what ever you want to do.
Now, we make FontUtils for set any .ttf font into our view.
public class FontUtils {
public static final int FONTS = 1;
public static final int FONTS_NORMAL = 2;
public static final int FONTS_BOLD = 3;
public static final int FONTS_BOLD1 = 4;
private static Map<String, Typeface> TYPEFACE = new HashMap<String, Typeface>();
static Typeface getFonts(Context context, String name) {
Typeface typeface = TYPEFACE.get(name);
if (typeface == null) {
typeface = Typeface.createFromAsset(context.getAssets(), name);
TYPEFACE.put(name, typeface);
}
return typeface;
}
public static void applyFont(TextView tv, int typefaceStyle) {
Context cxt = tv.getContext();
Typeface typeface;
if(typefaceStyle == Typeface.BOLD_ITALIC) {
typeface = FontUtils.getFonts(cxt, "FaktPro-Normal.ttf");
}else if (typefaceStyle == Typeface.BOLD || typefaceStyle == SD_FONTS_BOLD|| typefaceStyle == FONTS_BOLD1) {
typeface = FontUtils.getFonts(cxt, "FaktPro-SemiBold.ttf");
} else if (typefaceStyle == Typeface.ITALIC) {
typeface = FontUtils.getFonts(cxt, "FaktPro-Thin.ttf");
} else {
typeface = FontUtils.getFonts(cxt, "FaktPro-Normal.ttf");
}
if (typeface != null) {
tv.setTypeface(typeface);
}
}
}
It may be useful to know that starting from Android 8.0 (API level 26) you can use a custom font in XML.
You can apply a custom font to the entire application in the following way.
Put the font in the folder res/font.
In res/values/styles.xml use it in the application theme.
<style name="AppTheme" parent="{whatever you like}">
<item name="android:fontFamily">#font/myfont</item>
</style>
Fontinator is an Android-Library make it easy, to use custom Fonts.
https://github.com/svendvd/Fontinator
You can't extend TextView to create a widget or use one in a widgets layout:
http://developer.android.com/guide/topics/appwidgets/index.html

Categories