SVG on Android below API 23 [duplicate] - android

I am working on an Android project and I chose <vector> to display icon because it is adaptable and dynamically, however, I just can run this app on devices running Android, which have API 21 or higher. My question is how can I use <vector> on lower Android version i.e. API 14 or kind of. Thanks!
<!-- drawable/ic_android_debug_bridge.xml -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:height="48dp"
android:width="48dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path android:fillColor="#color/primaryColorDark"
android:pathData="M15,9A1,1 0 0,1 14,8A1,1 0 0,1 15,7A1,1 0 0,1 16,8A1,1 `0 0,1 15,9M9,9A1,1 0 0,1 8,8A1,1 0 0,1 9,7A1,1 0 0,1 10,8A1,1 0 0,1 9,9M16.12,4.37L18.22,2.27L17.4,1.44L15.09,3.75C14.16,3.28 13.11,3 12,3C10.88,3 9.84,3.28 8.91,3.75L6.6,1.44L5.78,2.27L7.88,4.37C6.14,5.64 5,7.68 5,10V11H19V10C19,7.68 17.86,5.64 16.12,4.37M5,16C5,19.86 8.13,23 12,23A7,7 0 0,0 19,16V12H5V16Z" /></vector>

With the support library 23.2, the true support for Vector Drawables has been provided all the way down to API v7.
It is recommended to disable the previous version of the support, which rendered PNG during build-time, by adding
// Gradle Plugin 2.0+
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
to the build.gradle file.
The implementation is fairly simple. Just use the new srcCompat attribute on Drawables (under app namespace!):
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#drawable/ic_add" /> // <= this is new
Vector Drawables are also supported in cases like TextView's drawableLeft property.
Source: library announcement
However, I would still recommend something like Iconics library, AndroidSVG, or another font-icon or SVG solution for the full SVG-standand vector support.

VectorDrawable are supported pre-Lollipop via the Support Library, but the way to use them depends on the version of Support Library you have. And it may not work in all cases.
I've made this diagram to help (valid for Support Library 23.4.0 to - at least - 25.1.0).

I found solution! For those who search solution with TextView and other "android" namespace attributes.
First of all this is necessary:
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
And in application class define this:
#Override
public void onCreate() {
super.onCreate();
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
Now you can use app:srcCompat="#drawable/ic_add" but if you try to use android:background= or android:drawableLeft= it will crash app with "Error inflating" exception.
We can create wrapped drawable ic_add_wrapped.xml for this vector:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/ic_add"/>
</layer-list>
And now it will work with any property like drawableLeft or background. Just set android:drawableLeft="#drawable/ic_add_wrapped.xml".
WARNING! THIS IS A WORKAROUND SOLUTION. So you use it for your own risk.

Vector Drawables are now backward compatible, it's just a matter of upgrading your gradle version to 1.4.0-beta3 or higher, and upgrade your IDE :
We are also excited to offer backwards compatibility for your vector
assets in Android Studio 1.4. Once you have a vectorDrawable image in
your res/drawable, the Gradle plugin will automatically generate
raster PNG images for API level 20 and below during build time. This
means you only need to update and maintain your vector asset for your
app project and Android Studio can take care of image conversion
process.
http://android-developers.blogspot.com.uy/2015/09/android-studio-14.html

you need use android Support Repository 30+ if you using android studio
and need android support library 23.2.1+ if using Eclipse.
check your build.gradle (project) if using version 2.0+ add below code in your build.gradle (app)
// Gradle Plugin 2.0+
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
and: if using version 1.5 add below in your build.gradle(app)
// Gradle Plugin 1.5
android {
defaultConfig {
generatedDensities = []
}
// This is handled for you by the 2.0+ Gradle Plugin
aaptOptions {
additionalParameters "--no-version-vectors"
}
}
here is sample code for use vector icon:
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#drawable/ic_add"
tools:ignore="MissingPrefix" />
or
<ImageButton
android:layout_width="wrap_content"
android:background="#android:color/transparent"
app:srcCompat="#drawable/camera"
tools:ignore="MissingPrefix"
android:layout_height="wrap_content"/>
Vector Drawables are also supported in cases like TextView's drawableLeft property. but it worked api 22+ to me and i still dont know how it will work for low api.
Also keep in mind if you want to be compatible below API 21:
you cannot use the android:background property in xml or View.setBackgroundResource() function. You need to use the View.setBackground().
you cannot use the svg-s in StateListDrawable xml-s or other xml drawables, you have to generate them programmatically.
you cannot use svg-s in case of notifications.

When you need to add VectorDrawable (created from SVG) programatically, you can do it like this:
icon = VectorDrawableCompat.create(resources, R.drawable.ic_map_black_24dp, null)

For lower version compatible,
add the below in gradle,
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
add the below code in onCreate() in your application class,
#Override
public void onCreate() {
super.onCreate();
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
In xml for imageView,
<ImageView
android:id="#+id/imageViewMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/transparent"
app:srcCompat="#drawable/ic_success"/>
If you want to change the image source programmatically use this,
imageView.setImageResource(R.drawable.ic_launcher);

I had an issue where my vector images would show up but would be completely black, this was due to an issue where you can't reference color resources in the vector xml file.
So instead of #color/primaryColorDark you have to use the actual color e.g. #212121

Just to make #2Dee's answer complete:
VectorDrawable cannot be used on API 20 and lower. The official method generates pngs, which then become BitmapDrawables, which breaks the idea of vector graphics.
Personally I prefer svg's over xml vectors:
such graphics can be exported right from Illustrator or other popular software
svg supports transformations, text, masks and other things properly
true scallable vector graphics on all platforms
smaller size and faster builds
To use vector graphics you can try https://github.com/BigBadaboom/androidsvg . It's an svg reader and svg-compatible ImageView.

If you are using Android Studio 3.0.0 you can set
android.enableAapt2=false
in gradle.properties
https://www.reddit.com/r/androiddev/comments/6mj8di/android_studio_30_canary_6_released/

You can use programatically ..to set drawableLeft to your editText or textView
like
Drawable tick_drawable = VectorDrawableCompat.create(getResources(), R.drawable.green_tick, null);
if (tick_drawable != null) {
tick_drawable.setBounds(0, 0, tick_drawable.getIntrinsicWidth(),tick_drawable.getIntrinsicHeight());
}
And to drawable left like this..
editText.setCompoundDrawables( tick_drawable , null, null, null );

after setting vectorDrawables.useSupportLibrary = true in gradle default and AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); in activity on create
To avoid crash with android:drawableleft in Textview, set drawble left to the textview programitically
for examlple:
textview.setCompoundDrawablesWithIntrinsicBounds(R.drawable.movie, 0, 0, 0);

I also found the same issue. And I did:
vectorDrawables.useSupportLibrary = true
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
textview.setCompoundDrawablesWithIntrinsicBounds(R.drawable.movie, 0, 0, 0);
It is good. But after that, I got an error that the resource not found.
So I found it's better to add a vector image according to the SDK version.
Finally, this solution became good is for me:-
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
textview.setCompoundDrawablesWithIntrinsicBounds(null, null, AppCompatResources.getDrawable(this, R.drawable.movie), null);
} else {
textview.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.movie, 0);
}
I hope, it will help someone.

Related

Xamarin - working with VectorDrawable in Imageview and Edittext

I face issue to apply vectordrawable at my imageView and Edittext
here is my tries to fix the issue
First I am using Xamarin.Android.Support.Vector.Drawable Version 23.4.0
Second I add AppCompatDelegate.CompatVectorFromResourcesEnabled = true; in onCreate of my Application
public class MyApplication : Application
{
public MyApplication(IntPtr handle, JniHandleOwnership ownerShip) : base(handle, ownerShip)
{
Log.Debug("App", "I am in oncreate application");
}
public override void OnCreate()
{
base.OnCreate();
AppCompatDelegate.CompatVectorFromResourcesEnabled = true;
}
}
*Third * usingAppCompatActivity to make sure my activity used AppCompatImageView instead of normal ImageView and try set drawable manually but it return with null (I dont know why this happen )
[Activity( Label = "Activity1", Theme = "#style/AppTheme")]
public class Activity1 : AppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.test);
ImageView testImage = FindViewById<ImageView>(Resource.Id.imageViewTest);
Drawable drawable = VectorDrawableCompat.Create(Resources, Resource.Drawable.ic_arrow_back_white_24dp, null);
testImage.SetImageDrawable(drawable);
}
}
Fourth in my project .csproj I add build tools version 23.0.3
<AndroidSdkBuildToolsVersion>23.0.3</AndroidSdkBuildToolsVersion>
here is my full file content
?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<AndroidSdkBuildToolsVersion>23.0.3</AndroidSdkBuildToolsVersion>
<AndroidDesignerPreferredDevice>Nexus 4</AndroidDesignerPreferredDevice>
<SelectedDevice>Nexus_5_API_21_x86</SelectedDevice>
<AndroidDesignerPreferredTheme>Theme.DeviceDefault</AndroidDesignerPreferredTheme>
</PropertyGroup>
</Project>
Fifth I reference my vector image app:srcCompat
but it still not working any one could help me fix this issue
I fix first half of my issue Simplly update to
Xamarin.Android.Support.Vector.Drawable Version 23.4.0.1
make sure you reference your vector images by this way app:srcCompat
related to EditText Image I think you cant set it from xml you need to use it via code here is the method
SetCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top, Drawable right, Drawable bottom);
in my case I used leftdrawable so my method look like
SetCompoundDrawablesWithIntrinsicBounds(Resource.Drawable.MyDrawable, 0, 0, 0);
hope this help any one face same issue
Update: Forget the Old Solution. Just update to the latest Verison of Xamarin (Xamarin.Android 7.2.0.7) and the latest version of the support libs (25.3.1).
Old Solution:
Downgrade to Xamarin 4.2.0.680, use only the support libs version 23.3.0 (Latest stable 24.2.1 crashes on Android 4.4.4 but works on Android 6)
Also ensure this:
Put this static constructor in your Activity:
static Activity1()
{
AppCompatDelegate.CompatVectorFromResourcesEnabled = true;
}
Or add AppCompatDelegate.CompatVectorFromResourcesEnabled = true; to your Application class´ OnCreate method.
<AndroidSdkBuildToolsVersion> in your project shouldn't be nessessary anymore.
Use app:srcCompat, like you already do.
Have a look at the Dependencies of each support lib at Nuget
I have:
Xamarin.Android.Support.Animated.Vector.Drawable.dll 23.3.0
Xamarin.Android.Support.Design.dll 23.3.0
Xamarin.Android.Support.v14.Preference.dll 23.3.0
Xamarin.Android.Support.v4.dll 23.3.0
Xamarin.Android.Support.v7.AppCompat.dll 23.3.0
Xamarin.Android.Support.v7.Preference.dll 23.3.0
Xamarin.Android.Support.v7.RecyclerView.dll 23.3.0
Xamarin.Android.Support.Vector.Drawable.dll 23.3.0
Also make shure you reference Java.Interop.dll
Try out another vector drawable, for example from Material Design Icons (Click on an icon, chose Icon Package, .XML Vector Drawable).

Android: remove deprecation warning for Html.fromHtml

I would like to remove the deprecation warning for Html.fromHtml(string).
I tried to do like this:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
htmlSpanned = Html.fromHtml(string,Html.FROM_HTML_MODE_LEGACY);
} else {
//noinspection deprecation
htmlSpanned = Html.fromHtml(string);
}
but it still gives me a warning during compilation:
Warning:(18, 31) [deprecation] fromHtml(String) in Html has been
deprecated
Well, the one-parameter fromHtml() is deprecated. The Build checks ensure that you will not call it on older devices, but it does not change the fact that it is deprecated with a compileSdkVersion of 24.
You have four choices:
Drop your compileSdkVersion below 24. This has rippling effects (e.g., you cannot use 24.x.x versions of the support libraries) and is not a great option.
Set your minSdkVersion to 24 and get rid of the one-parameter fromHtml() call. This is impractical in 2016.
Live with the strikethrough and Lint complaints.
Add the appropriate #SuppressLint annotation to the method, to get the IDE to stop complaining. As Ahlem Jarrar notes, the simplest way to add this is via the quick-fix.
If your minSdkVersion is 24 or higher, use the version of fromHtml() that takes some flags as a parameter . AFAIK, FROM_HTML_MODE_LEGACY would be the flag value to use for compatibility with the older flag-less fromHtml().
If your minSdkVersion is lower than 24, your choices are:
Always use the fromHtml() you are, possibly using the quick-fix (Alt-Enter) to suppress the Lint warning
Use both versions of fromHtml(): the one taking the flags if your app is running on an API Level 24+ device, or the one without the flags on older devices.
This was my solution at one point:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
textField.setText(Html.fromHtml(htmlText, Html.FROM_HTML_MODE_COMPACT));
} else {
textField.setText(Html.fromHtml(htmlText);
}
It worked just fine.
You can try it. I mean your code looks well, I tried it and it worked for me.
// get our html content
String htmlAsString = getString(R.string.html);
Spanned htmlAsSpanned = Html.fromHtml(htmlAsString);
// used by TextView
// set the html content on the TextView
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(htmlAsSpanned);
Our you can try it:
#SuppressWarnings("deprecation")
Android or Kotlin or Google has created HtmlCompat which can be used instead of the method Html. Add this dependency implementation 'androidx.core:core:1.0.1' to the build.gradle file of your app. Make sure you use the latest version of androidx.core:core.
This allows you to use:
HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY);
You can convert the HTML.FROM_HTML_MODE_LEGACY into an additional parameter if you want. This gives you more control about it which flag to use.
You can read more about the different flags on the HTML Class documentation

setBackgroundDrawable() is API 16 and my app requires a minimum API 9 I get no error when building

I have my app that requires SDK 9+ with code containing setBackgroundDrawable() which is API level 16. I did not get any error while coding or building the apk. but I got about 50 reports of this error happening in google analytics and a few reports in my developers console.
When I run the lint checker It also doesn't warn me. I am using eclipse. Is there a reason why it doesn't fail to compile like usually when you add a method that's not supported by the minimum API or is it simply an eclipse bug?
First of all you get no error when building since you probably are building with SDK 16+ and the method is there. But if you install the apk to a 2.1 Android phone it will throw a MethodNotFound Exception. So in the future ALWAYS install your apk on a min-target device to see if you didn't forget something. Min-Target basically is only a filter for the PLAY store (and for lint warnings, etc.)
AFAIK moving from imageView.setBackground(...) to imageView.setBackgroundDrawable(...) was just an api style design choice. So if you look at the source of Android SDK 18 you will see:
/**
* Set the background to a given Drawable, or remove the background. If the
* background has padding, this View's padding is set to the background's
* padding. However, when a background is removed, this View's padding isn't
* touched. If setting the padding is desired, please use
* {#link #setPadding(int, int, int, int)}.
*
* #param background The Drawable to use as the background, or null to remove the
* background
*/
public void setBackground(Drawable background) {
//noinspection deprecation
setBackgroundDrawable(background);
}
So for now its absolutely irrelevant if you use one or the other - but of course this COULD change (but it's unlikely it does in the future since it would break nearly every app done before SDK 16) - basically it's fine to use setBackground() even on SDK 18+
So if you want to be on the future-proof but ugly side you could use a version fork depicted by the other answers
if(Build.VERSION.SDK_INT >= 16) {
//new code
} else {
//deprecated code
}
Just one thing, and maybe this is a personal style preference, I would not suppress Lint warnings with annotations like this:
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
I like to keep the warnings since maybe later if I want to refactor/move to higher SDK I could easily get rid of these ugly switches.
Update:
Google's v4 support library contains helper classes for sdk boiler plate code. In this instance you would use:
ViewCompat.setBackground(view,drawable);
which handles the SDK check for you.
Seems to be a bug in eclipse or your eclipse is not working perfectly. But you can try project clean and try. But code wise you can try something like this:
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
public void setImage(ImageView imageView, BitmapDrawable bd) {
if(Build.VERSION.SDK_INT > 16) {
imageView.setBackground(bd);
} else {
imageView.setBackgroundDrawable(bd);
}
}
You can call this function along with ImageView and bitmap drawable.

Having issue on Real Device using vector image in android. SVG-android

I use svg-android.jar from https://github.com/pents90/svg-android at its work fine but only on emulator devices in eclipse. Agrrrr. On real devices it just empty imageView on screen.
here is my code:
SVG svg = SVGParser.getSVGFromResource(getResources(), R.raw.test);
Drawable drawable = svg.createPictureDrawable();
imgView.setImageDrawable(drawable);
any suggestion?
On newer devices that have hardware rendering turned on by default, you need to explicitly turn on software rendering.
imgView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
I suspect this is probably your problem.
Use AppCompatImageView instead ImageView in xml like the below code
<android.support.v7.widget.AppCompatImageView
android:tint="#d74313"
app:srcCompat="#drawable/circle_icon"
android:layout_width="30sp"
android:layout_height="30sp" />
and in your build.gradle
android {
defaultConfig {
vectorDrawables {
useSupportLibrary = true
}
}
}
If the above doesn't work, try this also in your application class
public class App extends Application {
#Override public void onCreate() {
super.onCreate();
// Make sure we use vector drawables
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
}

build for different targets conditionally

I have been building for API 14 so far. I'm trying to get ready now, so I downloaded and specified API 7 as my target. I have some compilation errors because a few api's I was using in API14 aren't available in API7.
I am wondering how I could put them in conditionals. Something on the lines of:
if (API_14)
{
if (mTextEdit.isEmpty()) {
// Do Something
}
} else if (API_7){
if (mTextEdit.matches("")) {
// Do the same thing
}
}
This has to be a compile time conditional switch because otherwise my code won't even compile.
I've heard before that pre-processors are not supported in Java, so I welcome suggestions on how best to manage my source which I'm targeting for multiple versions.
Edit:
I also am running into trouble with my state list drawable:
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:state_pressed="true"
android:drawable="#android:color/holo_orange_dark" />
<item android:drawable="#android:color/transparent" />
</selector>
Of course, hold_orange_dark isn't available in API7. I'd like to be able to manage those as well.
You can't do ifs, or you'll have a crash on older devices.
You have to use Java Reflection to use methods from more recent APIs conditionally.
An example: http://mobile.tutsplus.com/tutorials/android/java-reflection/
For your resources you can specify different directories for different platform versions. So you'd make a Values-v14 directory to have a copy of any resources that use anything from that API version and a Values directory so Values would be used by default and Values-v14 would only be used if the device was version 14.
As for doing it programmatically, you could try a Try-Catch like so-
try {
//Insert ICS stuff here
} catch(NoSuchMethodError e){
}
Or you could try this-
public static boolean isHoneycomb() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
}

Categories

Resources