Override resources in library android - android

I'm using my own library. In this library I defined some resources:
colors.xml (library)
<color name="colorPrimary">#000000</color>
In my app (that uses the above library). I want to override that color primary.
colors.xml (app)
<color name="colorPrimary">#ffffff</color>
I actually want to override that attribute so that the library (and my app) use the overrided one, not the declared one from library. It works fine but Android Studio keeps yelling out that:
Overriding #color/colorPrimary which is marked as private in my_lib. If deliberate, use tools:override="true", otherwise pick a different name". That makes me think that this is not a good approach.
I also try to add tools:override="true" to the resource:
<resources xmlns:tools="http://schemas.android.com/tools"
tools:override="true">
but the warning still there.
Is there any wrong with what I'm doing?. I can not pick another name because I want the library to use the overrided values.
I'm using Android Studio 2.1.1 and gradle 2.1.0 version.
Thanks.

Move the tools:override to the color tag.
There's nothing wrong with this. Android Studio is just warning you, incase it wasn't deliberate.
If you press alt-enter on the line with the warning, AS will offer to insert the override attribute for you and will put it in the correct place.

Related

Does Android Studio Linter Offer An Option to look for default XML layout values?

1.) Is there any reason to have a default value inside an android xml layout?
Ex.) The TextView below has included a default value of
android:visibility="visible"
`<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:visibility="visible"/>`
Conjecture: Because this is a default value, it has no effect, and therefore is an unnecessary line of code in the XML file. Is that line of thinking correct?
2.) If there is no reason for default values to exist in Android xml files, is there a lint plugin available to point out default value code lines in android XML files?
It is my thought that a large number of code lines in XML files are default values, serving no purpose. What can we do to reduce these lines of code?
U can create a style with your default values and use it.
For example:
<style name="DefaultTextViewStyle">
<item name="android:visibility">visible</item>
</style>
to use this:
<TextView
style="#style/DefaultTextViewStyle" />
I had some hope that the Lint inspection Redundant default value attribute assignment for xml, run via Android Studio might have done what you're asking. You can run it as specified under the Manually Run Inspections part of the Android docs. i.e.Android Studio -> Analyze -> Run Inspection by name -> enter "Redundant default value attribute assignment", then select the scope for the Lint check.
Sadly though, it doesn't pick up the case you mention above. I'm just wondering if there's something I've missed, or if this isn't intended for Android xml in some way?

Override layout xml from android framework

Problem
I want to override a layout file from android namespace, e.g. R.layout.popup_menu_item_layout (which is referenced from code as com.android.internal.R.layout.popup_menu_item_layout). By saying override, I assume declaring an xml file in the project which would be prioritized over the layout that framework owns.
Note, this is just an example layout, so the question concerns to each layout that's present in sdk/platforms/android-XX/data/res/layout directory.
What I've tried
tools:override
There's an undocumented tools:override tag available, which overrides specific resources. See this answer for an example, which overrides values from Design Support Library, not from Android framework.
Applying tools:override="true" to the root tag of the layout won't take effect.
XML layout references - refs.xml
As described in this post, declaring a refs.xml file in /values/ directory with following content:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item type="layout" name="activity_main">#layout/activity_second</item>
</resources>
will refer to activity_second.xml once activity_main.xml is used. There's an answer that suggests using this technique in order to substitute Snackbar's layout.
This also won't take effect.
Question
Is there any legitimate way to override/substitute a layout file from android package?
I know this is an old question but I also wanted to override a library layout with my own, here's how I did it.
The layout in question was called design_bottom_navigation_item
In refs.xml I added the following:
<resources xmlns:tools="http://schemas.android.com/tools">
<item name="design_bottom_navigation_item" type="layout" tools:override="true">#layout/bottom_navigation_item</item>
</resources>
There are 4 parts to this which I'll explain.
Name: This is the name of the layout you want to override
Type: The type of resource you are trying to override, in this case a layout.
tools:override: This is how you tell Android Studio to override the library layout with your own.
Value: This is where you specify what resource you want to use instead.
You can do this with any resource type this way.
What is that you're trying to do?
If the idea to only replace how the menu-item will look like, you can try the following:
Create a custom MyMenuAdapter extends MenuAdapter
Override the getView method to return the view from your adapter.
You are trying to customise your sdk on the application itself, at runtime.
That's just not how it works.
If you use an SDK on your project(on any technologies), and you need to modify some behavior, you will tweak this SDK and after that, compile your project with this news customized version.
Trying to modify it at runtime is not a good idea.
You will face multiple issues (retro compatibility, security trigger, TREBLE incompatibility , dependency issue, etc)
You have 4 possibilities to do what you want:
Make your own android rom where you will apply your modification
Copy the resources you need to modify on a fake xmlObject with the tag, after the onPostCreate of your application, you will be able to modify the when inflation. You can generalize this behavior and it will simulate an sdk overlay.
Make your own sdk :)
Multi-level reflection, but, no way you succeed with a stable version
Of course, none of this solutions is applicable for a public app.
don't know your issue have fixed or not but simple solution for this is create new layout that is same layout name of framework (in this case is popup_menu_item_layout). Then go to android google source to copy xml content popup_menu_item_layout
So you can custom anything u want. But remember don't change any id of views.

Error using "Theme.AppCompat" with Android Studio 2.1.0

In my android project, I am getting the error "Cannot find symbol for Theme.AppCompat" while using it in styles.xml file:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
I have included the app compat dependency in my gradle file:
'compile 'com.android.support:appcompat-v7:23.3.0'
I tried finding the solution all over internet but nothing helps. Can someone help me with this..
Just wanted to let you know that you're not alone. Everything was working fine in the app I was developing, testing heavily on a marshmallow nexus 5 and a lollipop samsung tablet. I must have let something automatically update, because now I'm having problems with appcompat.
Here's an example of what's going wrong:
in a layout XML I have an edit text with style specified:
style="#style/Widget.AppCompat.EditText"
This will cause 'Error inflating class EditText'
if I create a style for the edit text in v21 styles with a parent of 'Widget.AppCompat.EditText' and specify the background (my color, or drawable, or ?android:attr/editTextStyle) it will work - though all of these options lose the edittext underline style.
If I specify background of ?attr/editTextStyle it will fail to inflate, which I assume is the default, it will fail to inflate. Likewise, if I leave any style tag off of the edit text, it will also fail to inflate.
Glad I'm not alone, but I wish this wasn't a thing...

Using android vector Drawables on pre Lollipop crash

I'm using vector drawables in android prior to Lollipop and these are of some of my libraries and tool versions:
Android Studio : 2.0
Android Gradle Plugin : 2.0.0
Build Tools : 23.0.2
Android Support Library : 23.3.0
I added this property in my app level Build.Gradle
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
It is also worth mentioning that I use an extra drawable such as LayerDrawable(layer_list) as stated in Android official Blog (link here) for setting drawables for vector drawables outside of app:srcCompat
<level-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/search"/>
</level-list>
You’ll find directly referencing vector drawables outside of
app:srcCompat will fail prior to Lollipop. However, AppCompat does
support loading vector drawables when they are referenced in another
drawable container such as a StateListDrawable, InsetDrawable,
LayerDrawable, LevelListDrawable, and RotateDrawable. By using this
indirection, you can use vector drawables in cases such as TextView’s
android:drawableLeft attribute, which wouldn’t normally be able to
support vector drawables.
When I'm using app:srcCompat everything works fine, but when I use:
android:background
android:drawableLeft
android:drawableRight
android:drawableTop
android:drawableBottom
on ImageView, ImageButton, TextView or EditText prior to Lollipop, it throws an expection:
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/search_toggle.xml from drawable resource ID #0x7f0200a9
LATEST UPDATE - Jun/2019
Support Library has changed a bit since the original answer. Now, even the Android plugin for Gradle is able to automatically generate the PNG at build time. So, below are two new approaches that should work these days. You can find more info here:
PNG Generation
Gradle can automatically create PNG images from your assets at build time. However, in this approach, not all xml elements are supported. This solution is convenient because you don't need to change anything in your code or in your build.gradle. Just make sure you are using Android Plugin 1.5.0 or higher and Android Studio 2.2 or higher.
I'm using this solution in my app and works fine. No additional build.gradle flag necessary. No hacks is necessary. If you go to /build/generated/res/pngs/... you can see all generated PNGs.
So, if you have some simple icon (since not all xml elements are supported), this solution may work for you. Just update your Android Studio and your Android plugin for Gradle.
Support Library
Probably, this is the solution that will work for you. If you came here, it means your Android Studio is not generating the PNGs automatically. So, your app is crashing.
Or maybe, you don't want Android Studio to generate any PNG at all.
Differently from that "Auto-PNG generation" which supports a subset of XML element, this solution, supports all xml tags. So, you have full support to your vector drawable.
You must first, update your build.gradle to support it:
android {
defaultConfig {
// This flag will also prevents Android Studio from generating PNGs automatically
vectorDrawables.useSupportLibrary = true
}
}
dependencies {
// Use this for Support Library
implementation 'com.android.support:appcompat-v7:23.2.0' // OR HIGHER
// Use this for AndroidX
implementation 'androidx.appcompat:appcompat:1.1.0' // OR HIGHER
}
And then, use app:srcCompat instead of android:src while loading VectorDrawables. Don't forget this.
For TextView, if you are using the androidx version of the Support Library, you can use app:drawableLeftCompat (or right, top, bottom) instead of app:drawableLeft
In case of CheckBox/RadioButton, use app:buttonCompat instead of android:button.
If you are not using the androidx version of the Support Library and your minSdkVersion is 17 or higher or using a button, you may try to set programmatically via
Drawable icon = AppCompatResources.getDrawable(context, <drawable_id>);
textView.setCompoundDrawablesWithIntrinsicBounds(<leftIcon>,<topIcon>,<rightIcon>,<bottomIcon>);
UPDATE - Jul/2016
They re-enabled that VectorDrawable in
Android Support Library 23.4.0
For AppCompat users, we’ve added an opt-in API to re-enable support Vector Drawables from resources (the behavior found in 23.2) via AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) - keep in mind that this still can cause issues with memory usage and problems updating Configuration instances, hence why it is disabled by default.
Maybe, build.gradle setting is now obsolete and you just need to enable it in proper activities (however, need to test).
Now, to enable it, you must do:
public class MainActivity extends AppCompatActivity {
static {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
...
}
Original Answer - Apr/2016
I think this is happening because Support Vector was disabled in the latest library version: 23.3.0
According to this POST:
For AppCompat users, we’ve decided to remove the functionality which let you use vector drawables from resources on pre-Lollipop devices due to issues found in the implementation in version 23.2.0/23.2.1 (ISSUE 205236). Using app:srcCompat and setImageResource() continues to work.
If you visit issue ISSUE 205236, it seems that they will enable in the future but the memory issue will not be fixed soon:
In the next release I've added an opt-in API where you can re-enable the VectorDrawable support which was removed. It comes with the same caveats as before though (memory usage and problems with Configuration updating).
I had a similar issue. So, in my case, I reverted all icons which use vector drawable from resource to PNG images again (since the memory issue will keep happening even after they provide an option to enable it again).
I'm not sure if this is the best option, but it fixes all the crashes in my opinion.
I had the same problem.
But doing a lot of R&D I got the answer.
For Imageview and ImageButton use,app:srcCompat="#drawable/...."
and for other views like Button, Textview, instead of using "drawableLeft/right..." in the XML, specify drawables programmitically as :
button.setCompoundDrawablesWithIntrinsicBounds(AppCompatResources.getDrawable(mContext,R.drawable.ic_share_brown_18dp), null, null, null);
And use "AppCompatResources" to get the drawable.
To elaborate on the other very good answers, here is a diagram that can help you. It is valid if you have Support Library from 23.4.0 to at least 25.1.0.
The answer from Guillherme P is pretty awesome. Just to make a small improvement, you don't need to add that line in every activity, if you added it once in the Application class it will work as well.
public class App extends Application {
static {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
REMEMBER: You still need to have enabled the use of the support library in gradle:
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
Also, make sure you are using a support library version greater than v23.4, when Google added back the support for Drawable Containers for VectorDrawables (release note)
Update
And for code changes:
Make sure to update to app:srcCompat every place that accepts the android:src attribute (the IDE will warn you if it's invalid like for the <bitmap> tag).
For drawableLeft, drawableStart, drawableRight, drawableEnd attributes used in TextView and similar views, you will have to set them programmatically for now. An example of setting drawableStart:
Drawable drawable = AppCompatResources.getDrawable(
getContext(),
R.drawable.your_vector_drawable);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
textView.setCompoundDrawablesRelativeWithIntrinsicBounds(drawable, null, null, null);
}
I had the same problem. And fix it by removing
vectorDrawables.useSupportLibrary = true
My target version is 25 and support library is
compile 'com.android.support:appcompat-v7:25.3.1'
VectorDrawables on pre-lollipop should work fine without using
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
If you want to use VectorDrawables inside ImageViews, you can use the attribute srcCompat and it will work, but inside Buttons or TextViews it won't, so you need to wrap the Drawable into an InsetDrawable or a LayerDrawable. There is another trick I discovered, if you are using data binding, you could do this:
android:drawableLeft="#{#drawable/vector_ic_access_time_24px}"
android:drawableStart="#{#drawable/vector_ic_access_time_24px}"
That will magically work, I haven't investigated what's happening behind the scenes, but I guess the TextView is using the getDrawable method from the AppCompatResources or similar.
Lot of R & d, finally getting this solution for crashes on pre-lollipop devices.
For Imageview
use app:srcCompat instead of android:src
For TextView/EditText
Remove drawableleft,drawableright.... and set from drawable java code.
txtview.setCompoundDrawablesWithIntrinsicBounds(AppCompatResources.getDrawable(EventDetailSinglePage.this,
R.drawable.ic_done_black_24_n), null, null, null);
For Build.gradle
vectorDrawables.useSupportLibrary = true
Easiest way use :
app:drawableRightCompat ="#drawable/ic_mobilelogin"
app:drawableEndCompat="#drawable/ic_mobilelogin"
app:srcCompat="#drawable/ic_mobile"
and... just use app:**Compatfor compatability.
Also add support on build.gradle (module)
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
For anyone who upgrade to android gradle 3.0 and above, there is no need to use AppCompatDelegate.setCompatVectorFromResourcesEnabled(true), or set vectorDrawables.useSupportLibrary = true (add this will cause problem) and use app:srcCompat, it just works.
Take me two days to figure this out, and have not find any related docs in google's docs...
After using the below code.
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
public class App extends Application {
static {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}}
still, vector images issue exists for below attributes are
DrawableEnd,
DrawableStart,
DrawableTop,
DrawableBottom,
Background
In this case, please follow as below, Instead of referencing vector image directly use selector tag as an intermediate drawable file.
Example:
ic_warranty_icon.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="17dp"
android:height="24dp"
android:autoMirrored="true"
android:viewportWidth="17"
android:viewportHeight="24">
<path
android:fillColor="#fff"
android:pathData="M10.927,15.589l-1.549,0.355a7.47,7.47 0,0 1,-0.878 0.056c-4.136,0 -7.5,-3.364 -7.5,-7.5s3.364,-7.5 7.5,-7.5 7.5,3.364 7.5,7.5c0,3.286 -2.126,6.078 -5.073,7.089zM8.5,2a6.508,6.508 0,0 0,-6.5 6.5c0,3.583 2.917,6.5 6.5,6.5s6.5,-2.917 6.5,-6.5 -2.917,-6.5 -6.5,-6.5z" />
safe_ic_warranty_icon.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/ic_warranty_icon" />
</selector>
Your TextView/Layout.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableStart="#drawable/ic_warranty_icon"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/ic_warranty_icon"
/>
I am using VectorDrawables on Pre-lollipop devices and this is how I do it :-
Step 1:
Put this in your app level gradle.
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
Step 2:
Put this in your Application class and don't forget to register your Application class in the manifest file.
public class App extends Application {
static {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
}
Step 3:
Get VectorDrawables using,
imageView.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.my_vector_drawable));
We tried 3 things
vectorDrawables.useSupportLibrary = true
Setting setCompatVectorFromResourcesEnabled in Application class
static {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
And use app:srcCompat
But even after that it was failing with
Resources$NotFoundException: File res/drawable/$my_icon__0.xml from color state list resource ID #0x7f080008
then we figured out that our SVG had a Gradient tag.
Converting the gradient tag to individual paths for below API <= 23 and using the same SVG API >= 24 worked.
Got help from this answer https://stackoverflow.com/a/47783962/2171513
I was struggling with this for hours.
I tried everything these answers told me to, but my app didn't stop crashing. I deleted this line: app:srcCompat="#drawable/keyboard" and my app stopped crashing. and then when I added this same thing back, it started crashing again. So I decided to open that file and I saw an error at the first line saying
"The drawable 'Keyboard' has no declaration in the base drawable
folder; this can lead to crashes.
I right-clicked the file and clicked "Show in explorer" and it was not in the drawable folder but in the drawable-v24 directory. So I copied it and pasted to the drawable directory and finally got rid of crashes.
Simply overlap vector drawable to state-list then problem will be solved
For example you have back arrow vector image:
ic_back_arrow.xml
yes, you should overlap it to layer list xml (ic_back_arrow_vector_vector.xml):
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/ic_back_arrow"/>
</layer-list>
Because logic:
vectorDrawables.useSupportLibrary = true
and
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
will not help you on the some China devices and older samsung devices. If you do not overlap them, it will fail.
In my case, I was using a TabLayout, which I configured as it :
TabLayoutMediator(tabLayout!!, viewPager!!) { tab, position ->
if (position == 0)
tab.icon = ResourcesCompat.getDrawable(resources, R.drawable.ic_list, theme)
else
tab.icon = ResourcesCompat.getDrawable(resources, R.drawable.ic_building_map, theme)
}.attach()
The app was crashing at line tab.icon = ...
I change these to tab.setIcon(R.drawable.my_vector_asset), as it :
TabLayoutMediator(tabLayout!!, viewPager!!) { tab, position ->
if (position == 0)
tab.setIcon(R.drawable.ic_list)
else
tab.setIcon(R.drawable.ic_building_map)
}.attach()
And it worked !
Guilherme P's suggestion was not working for me. I went ahead and made the decision to use png's where I need to do things outside of app:srcCompat i.e. drawableLeft, drawableRight, etc. This was a pretty easy change to make, and doesn't have the potential memory issues AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
introduces.
An alternative to Benny's answer is to create an Activity superclass:
public abstract class VectorDrawableActivity extends AppCompatActivity {
static {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
//...
}
Now extend VectorDrawableActivity instead of AppCompatActivity.

Xamarin Colors Causing Build Errors

I have an android application built with Xamarin Studio. I added a file named colors.xml to the Resources/values folder. The contents were:
<resources>
<color name="ViewBackgroundColor">#ffffff</color>
</resources>
To that, I was following this approach to define and use it; however, I was trying to apply it to the view's root element (found that resource elsewhere on SO, don't have exact link). So I applied it to the view by adding android:background="#color/ViewBackgroundColor" attribute to the root element. However, this generates a build error that #color/ViewBackgroundColor isn't a value. is anybody else having this issue and is there a resolution?
To reference that color, you must use all lowercase letters.
So
android:background="#color/viewbackgroundcolor"
This is because the Xamarin tools lowercases all names to be compliant with the rules Android has for resource names.
Is also important to set "Build Action" (with mouse right button on file color.xml) as AndroidResource.

Categories

Resources