Repository: Cricin/Folivora
Branch: master
Commit: e2beb4637a8b
Files: 45
Total size: 247.9 KB
Directory structure:
gitextract_92jzfoma/
├── .gitignore
├── LICENSE
├── README-zh.md
├── README.md
├── android_release_aar.gradle
├── build.gradle
├── folivora/
│ ├── build.gradle
│ └── src/
│ └── main/
│ ├── AndroidManifest.xml
│ ├── java/
│ │ └── cn/
│ │ └── cricin/
│ │ └── folivora/
│ │ ├── DrawableParser.java
│ │ ├── Folivora.java
│ │ ├── FolivoraInflater.java
│ │ ├── FolivoraViewFactory.java
│ │ ├── OnViewCreatedListener.java
│ │ ├── ParseRequest.java
│ │ ├── RippleFallback.java
│ │ └── ShapeAttrs.java
│ └── res/
│ └── values/
│ └── attrs.xml
├── gradle/
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── lint/
│ ├── build.gradle
│ └── src/
│ └── main/
│ └── java/
│ └── cn/
│ └── cricin/
│ └── folivora/
│ ├── dom/
│ │ ├── AndroidFacetCompat.java
│ │ ├── DrawableIdConverter.java
│ │ ├── FolivoraAttrProcessing.java
│ │ └── FolivoraDomExtender.java
│ ├── lint/
│ │ ├── FolivoraIssueRegistry.java
│ │ ├── InstalledBeforeSuperDetector.java
│ │ ├── InternalFolivoraApiDetector.java
│ │ └── PreferStubViewDetector.java
│ └── preview/
│ ├── FolivoraPreview.java
│ └── ViewFactory.java
├── sample/
│ ├── build.gradle
│ └── src/
│ └── main/
│ ├── AndroidManifest.xml
│ ├── java/
│ │ └── cn/
│ │ └── cricin/
│ │ └── folivora/
│ │ └── sample/
│ │ ├── MainActivity.java
│ │ └── drawable/
│ │ ├── AlphaBackgroundDrawable.java
│ │ ├── UmbrellaDrawable.java
│ │ └── WindmillDrawable.java
│ └── res/
│ ├── layout/
│ │ └── activity_main.xml
│ └── values/
│ ├── attrs.xml
│ ├── colors.xml
│ ├── strings.xml
│ └── styles.xml
└── settings.gradle
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Built application files
*.apk
*.ap_
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# IntelliJ
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
.idea/caches
# Keystore files
# Uncomment the following line if you do not want to check your keystore files in.
#*.jks
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
# Google Services (e.g. APIs or Firebase)
google-services.json
# Freeline
freeline.py
freeline/
freeline_project_description.json
# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md
preview_support/libs/*.jar
.idea/
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README-zh.md
================================================
### 为什么需要Folivora
对于android开发者来说,在layout文件中引用drawable来设置`View`的背景或者`ImageView`的`src`是很常见的事情,需要我们在drawable文件夹下写好xml文件就可以应用了,但是有许多drawable文件可能只被使用了一次,也有可能我们只是为了实现一个简单的圆角背景的功能。越来越多的drawable文件导致开发和维护成本的增加,有没有什么方法可以直接在layout文件中去创建drawable呢,Folivora为你提供了这样的功能。
### Folivora能做什么
Folivora可以为你的View设置一个背景或者ImageView的src,当前支持的drawable类型有
* shape (GradientDrawable)
* selector (StateListDrawable)
* ripple (RippleDrawable)
* layerlist (LayerListDrawable)
* levellist (LevelListDrawable)
* inset (InsetDrawable)
* clip (ClipDrawable)
* scale (ScaleDrawable)
* animation (AnimationDrawable)
* 自定义的Drawable **(新增)**
### 使用方法
- **STEP1** :
添加Gradle依赖,在项目的build.gradle中加入
```groovy
dependencies {
implementation 'cn.cricin:folivora:0.1.0'
}
```
- **STEP2** :
在layout.xml中加入自定义的属性, 告诉Folivora如何创建drawable,Folivora提供的内置drawable属性前缀如下
* shape -> shape
* selectror -> selector
* layer-list -> layer
* level-list -> level
* clip -> clip
* scale -> scale
* inset -> inset
* ripple -> ripple
* animation -> anim
例如所有的shape属性设置的前缀都是shape, 如`shapeSolidColor`, `shapeCornerRadius`等, 在设置了`drawableType`
之后,敲出指定的前缀,IDE会自动的给出所有该drawableType可用的属性
> shape
我们来试着在xml中书写Folivora为我们提供的属性来实现上图中第一个的圆角shape效果
```xml
```
我们在看一下其他几种drawable的用法:
> layerlist
```xml
```
> levellist
```xml
```
> selector
```xml
```
在0.0.7版本中,Folivora加入了对创建复杂state的selector支持,使用app:selectorItemXStates指定需要的state flags,使用app:selectorItemXDrawable指定对应states的drawable(X可以是0,1,2,3,4),现在可以用新的方式实现上面的drawable。
```xml
```
注:两种selector写法最好不要混用,推荐使用新的selector写法,这种方式的selector顺序是严格按照item定义的顺序添加进selector的,唯一的限制是只能定义5个states和drawables,不过对于一般的selector应该够用了
> ripple
```xml
```
使用ripple的确是酷炫多了,但是ripple效果是5.0之后引入的,那5.0之前的设备怎么办呢,Folivora为你提供了`RippleFallback`接口,用来创建一个替换`RippleDrawable`的`Drawable`实例,让我们试着用一个selector来代替ripple:
```java
Folivora.setRippleFallback(new Folivora.RippleFallback()){
@Override
public Drawable onFallback(ColorStateList ripple, Drawable content, Drawable mask, Context ctx){
StateListDrawable sld = new StateListDrawable();
sld.addState(new int[]{android.R.attr.state_pressed}, new ColorDrawable(ripple.getDefaultColor()));
sld.addState(new int[0], content);
return sld;
}
}
```
> clip
```xml
```
> inset
```xml
```
> scale
```xml
```
> animation
```xml
```
注: 如果你在layout文件中用Folivora为系统控件添加drawable,如`View`和`TextView`等,许多 IDE (Android Studio, IntelliJ) 会把这些Folivora提供的属性标注为错误,但是实际上是正确的。可以在这个View或者根ViewGroup上加上`tools:ignore="MissingPrefix"`来避免报错。为了使用 `ignore`属性,可以加上`xmlns:tools=" http://schemas.android.com/tools"`。关于这个问题,可以查看: https://code.google.com/p/android/issues/detail?id=65176.
- **STEP3** :
在Activity中启用Folivora, 有两种方法:
1.
```java
public class MainActivity extends Activity {
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(Folivora.wrap(newBase));
}
}
```
2.
```java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Folivora.installViewFactory(this);
setContentView(R.layout.your_layout_xml_name);
}
}
```
### 使用嵌套的shape
Folivora现在支持在drawable中嵌套shape了,除了animation以外,所有的drawable的子drawable除了可以使用`@drawable/xxx`和颜色之外,新增了shape/shape1/shape2/shape3/shape4这5个值,参考定义shape的例子,替换相应的前缀即可, 我们来定义嵌套了shape的selector试一试
```xml
```
效果是这样的
### 使用自定义Drawable
从0.0.4版本开始,Folivora除了支持自带的drawable以外,还支持使用自定的drawable类型了,让你使用自定义drawable就和使用自定义view一样轻松。这里我们以自定义一个绘制纸风车的`WindmillDrawable`为例,来让Folivora为我们提供支持:
1. 首先我们和自定义`View`一样,为`WindmillDrawable`提供自定义的属性:
```xml
```
可以看到,自定义属性这部分和普通的`View`自定义属性是一样的。name和自定义drawable的类名相同就行了,Folivora就可以在layout文件中为这些drawable的自定义属性提供属性的自动提示了
2. 创建自定义的`WindmillDrawable`,继承自`Drawable`, 提供一个`public WindmillDrawable(Context ctx, AttributeSet attrs)`的构造方法,在这个构造方法里就可以获取自定义的属性, 代码如下:
```java
public WindmillDrawable(Context ctx, AttributeSet attrs) {
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.WindmillDrawable);
int count = a.getIndexCount();
for (int i = 0; i < count; i++) {
int index = a.getIndex(i);
switch (index) {
case R.styleable.WindmillDrawable_wdSize:
mSize = a.getDimensionPixelSize(index, mSize);
break;
case R.styleable.WindmillDrawable_wdColor0:
mColors[0] = a.getColor(index, mColors[0]);
break;
case R.styleable.WindmillDrawable_wdColor1:
mColors[1] = a.getColor(index, mColors[1]);
break;
...
default://no-op unexpected attr index
break;
}
}
a.recycle();
}
```
这部分代码其实和自定义`View`的属性获取没有什么区别,主要就是给drawable添加一个构造方法,具体绘制代码就不贴了,如果想要查看具体细节,可以点击[这里](https://github.com/Cricin/Folivora/blob/master/sample/src/main/java/cn/cricin/folivora/sample/drawable/WindmillDrawable.java)查看源码
3. 在layout文件中使用自定义drawable,Folivora提供了`drawableName`属性,使用该属性指定需要使用的drawable:
```xml
```
运行之后的效果:
到这里,Folivora就会为该`View`设置我们指定的drawable了,有人可能就会问了,drawable名字这么长,写起来会不会太复杂了,不用担心,当你敲出drawableName的时候,Folivora会为你自动提示可用的drawable名字的,并且该drawable的自定义属性也会有自动提示。
> 如果我的自定义drawable没有上面指定的构造方法,并且我没办法直接修改该drawable的源码来添加这个构造方法该怎么办呢?
Folivora考虑到了这一点,有些drawable的源码我们没法修改,但是它总会有向外提供设置属性的方法吧?所以,我们提供了一个`DrawableFactory`接口,假设`WindmillDrawable`只有一个无参的构造方法,但是提供了设置各种属性的方法,我们需要让Folivora支持`WindmillDrawable`,可以这样做:
```java
Folivora.addDrawableFactory(new Folivora.DrawableFactory() {
@Override
public Drawable newDrawable(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.WindmillDrawable);
WindmillDrawable d = new WindmillDrawable();
d.setColor0(a.getColor(R.styleable.WindmillDrawable_wdColor0, Color.BLACK));
d.setRotateDegrees(a.getInt(R.styleable.WindmillDrawable_wdRotateDegrees, 0));
...
a.recycle();
return d;
}
@Override
public Class extends Drawable> drawableClass() {
return WindmillDrawable.class;
}
});
```
> 自定义Drawable请注意,如果你的drawable需要获取其他drawable,建议使用`Folivora.getDrawable(Context ctx, TypedArray a, AttributeSet attrs, int attrIndex)`方法获取,这样可以支持获取内嵌的`shape`,当然如果你不需要支持内嵌的`shape`,可以不用这样做。
### 使用Drawable缓存
在之前的版本中,Folivora会根据view tag中的属性创建drawable,每次都会创建一个新的drawable实例,很浪费资源,现在Folivora支持了drawable的缓存功能(LruCache,大小为128), 使用缓存非常简单,只需要添加`app:drawableId`属性,为drawable指定一个id(string类型,不是android的id类型)即可。Folivora在为view设置drawable的时候,如果drawable在缓存中,会直接从缓存中取。这就带来了一个便利,如果在一个layout文件中,一个drawable被多次使用,只需要在第一次使用的地方编写drawable定义就行了,其他的地方可以直接使用drawableId引用该drawable。
```xml
```
建议为需要复用的drawable和经常使用的layout文件中的drawable设置`drawableId`, 以提升性能。
### 下载示例APK
[点击下载](https://raw.githubusercontent.com/Cricin/Folivora/master/sample.apk)
### 编辑layout文件时的预览
> 预览效果
依赖了Folivora之后,默认是可以直接预览的,如果没有效果,尝试build一下你的项目。
### Folivora支持的属性列表
##### 通用属性
属性 | 取值| 描述
---|--- | --- |
app:setAs|background(default) | src | foreground| 设置view背景或者ImageView的src或者view前景
app:drawableType|shape | layer_list | selector | ripple | clip | scale | animation | level_list|drawable类型
app:drawableName|string|自定义drawable的class全名
app:drawableId|string|用于缓存的drawable唯一id
##### shape属性
属性 | 取值| 描述
---|--- | --- |
app:shapeType|rectangle(default)|oval|line|ring|形状
app:shapeSolidSize|dimension|宽高
app:shapeSolidWidth|dimension|宽
app:shapeSolidHeight|dimension|高
app:shapeSolidColor|color|填充色
app:shapeSolidColor|color|边框填充色
app:shapeStokeWidth|dimension|边框厚度
app:shapeStokeDashWidth|dimension|边框线宽
app:shapeStokeDashGap|dimension|边框线间距
app:shapeCornerRadius|dimension|角半径
app:shapeCornerRadiusTopLeft|dimension|左上角半径
app:shapeCornerRadiusTopRight|dimension|右上角半径
app:shapeCornerRadiusBottomLeft|dimension|坐下角半径
app:shapeCornerRadiusBottomRight|dimension|右下角半径
app:shapeGradientType|linear | radial | sweep|渐变类型
app:shapeGradientAngle|tb | tr_bl | rl | br_tl | bt | bl_tr | lr | tl_br|渐变角度
app:shapeGradientStartColor|color|渐变起始颜色
app:shapeGradientCenterColor|color|渐变中间颜色
app:shapeGradientEndColor|color|渐变结束颜色
app:shapeGradientRadius|dimension|渐变半径
app:shapeGradientCenterX|float|渐变中点x轴位置
app:shapeGradientCenterY|float|渐变中点y轴位置
##### selector属性
属性 | 取值| 描述
---|--- | --- |
app:selectorStateFirst|reference | color|selector状态:第一个
app:selectorStateMiddle|reference | color|selector状态:中间
app:selectorStateLast|reference | color|selector状态:最后一个
app:selectorStateActive|reference | color|selector状态:活动
app:selectorStateActivated|reference | color|selector状态:激活的
app:selectorStateAccelerate|reference | color|selector状态:加速的
app:selectorStateChecked|reference | color|selector状态:勾选的
app:selectorStateCheckable|reference | color|selector状态:可勾选的
app:selectorStateEnabled|reference | color|selector状态:启用的
app:selectorStateFocused|reference | color|selector状态:获得焦点
app:selectorStatePressed|reference | color|selector状态:点击
app:selectorStateNormal|reference | color|selector状态:正常状态
##### layerlist属性
属性 | 取值| 描述
---|--- | --- |
app:layerItem0Drawable| reference | color| 最底层的drawable
app:layerItem0Insets|dimension|该drawable的margin
app:layerItem0Left|dimension| 该drawable的左margin
app:layerItem0Right|dimension|该drawable的右margin
app:layerItem0Top|dimension|该drawable的上margin
app:layerItem0Bottom|dimension|该drawable的下margin
...
layerlist支持最多5个drawable,替换相应的数字即可
##### ripple属性
属性 | 取值| 描述
---|--- | --- |
app:rippleColor|color|ripple点击时的涟漪色
app:rippleMask|reference | color|ripple涟漪色的遮罩
app:rippleContent|reference | color|ripple的内容背景
如果设备不支持Ripple效果(
### Usage
- **STEP1** :
gradle dependency, add below in your project's build.gradle
```groovy
dependencies {
implementation 'cn.cricin:folivora:0.1.0'
}
```
- **STEP2** :
write down the attribute provided by folivora, tell folivora how to create drawable, prefix of drawables folivora builtin supported are:
* shape -> shape
* selectror -> selector
* layer-list -> layer
* level-list -> level
* clip -> clip
* scale -> scale
* inset -> inset
* ripple -> ripple
* animation -> anim
for example, all attributes prefix of a GradientDrawable is shape, like `shapeSolidColor`, `shapeCornerRadius`, IDE will gives you all available attributes after you write down `drawableType` and typed the drawable prefix.
> shape
let's try to write down some code to introduce how folivora works with the first view above
```xml
```
here are some other supported drawable usages:
> layerlist
```xml
```
> levellist
```xml
```
> selector
```xml
```
since 0.0.7,Folivora added support about complicated state selector,use `app:selectorItemXStates` to set state flags,and use `app:selectorItemXDrawable` set corresponding drawable to the states(X can be 0,1,2,3,4),now we can use the new way to describe drawable above。
```xml
```
Note:it is recommended to not mixed two selector definitions,just use the new way is better,which is ordered when add in selector by item index, constraint is only support 5 items for now, which is enough for usual selectors.
> ripple
```xml
```
much cooler after used ripple drawable, but ripple effect is introduced in lollipop, if the device platform version is lower than lolipop, folivora provided a `RippleFallback` for you, you can provide a substitude drawable if ripple is unavailable, let's try a create a `selector` instead of `ripple`:
```java
Folivora.setRippleFallback(new RippleFallback()){
@Override
public Drawable onFallback(ColorStateList ripple, Drawable content, Drawable mask, Context ctx){
StateListDrawable sld = new StateListDrawable();
sld.addState(new int[]{android.R.attr.state_pressed}, new ColorDrawable(ripple.getDefaultColor()));
sld.addState(new int[0], content);
return sld;
}
}
```
> clip
```xml
```
> inset
```xml
```
> scale
```xml
```
> animation
```xml
```
_Note: Popular IDE's (Android Studio, IntelliJ) will likely mark this as an error despite being correct. You may want to add `tools:ignore="MissingPrefix"` to either the View itself or its parent ViewGroup to avoid this. You'll need to add the tools namespace to have access to this "ignore" attribute. `xmlns:tools="
http://schemas.android.com/tools"`. See https://code.google.com/p/android/issues/detail?id=65176._
- **STEP3** :
enable folivora in your app, there are two ways:
```java
public class MainActivity extends Activity {
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(Folivora.wrap(newBase));
}
}
```
or
```java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Folivra.installViewFactory(this);
setContentView(R.layout.your_layout_xml_name);
}
}
```
#### Use nested shape
Folivora now support nest shape in drawable, except `animation`, all drawable's child drawable can use `@drawable/xxx`, a color, or one of shape/shape1/shape2/shape3/shape4, you can use this prefix combine with the shape attrs, let's define two round corner shape nested in selector:
```xml
```
effect is:
### Use custom drawable
since 0.0.4,Folivora support use custom drawable, makes it easyly to use custom drawables just like custom views,for example, let's write a `WindmillDrawable` which draws a paper windmill:
1. first, write down some attrs we needed for `WindmillDrawable`, just like the way of custom view:
```xml
```
Note: declare-styleable name must equals with the drawable's simple class name, so folivora will support code completion about the custom attrs.
2. Create a `WindmillDrawable`,extends `Drawable`, provide a `public WindmillDrawable(Context ctx, AttributeSet attrs)` constructor,you can retrieve custom attrs here, like this:
```java
public WindmillDrawable(Context ctx, AttributeSet attrs) {
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.WindmillDrawable);
int count = a.getIndexCount();
for (int i = 0; i < count; i++) {
int index = a.getIndex(i);
switch (index) {
case R.styleable.WindmillDrawable_wdSize:
mSize = a.getDimensionPixelSize(index, mSize);
break;
case R.styleable.WindmillDrawable_wdColor0:
mColors[0] = a.getColor(index, mColors[0]);
break;
case R.styleable.WindmillDrawable_wdColor1:
mColors[1] = a.getColor(index, mColors[1]);
break;
...
default://no-op unexpected attr index
break;
}
}
a.recycle();
}
```
this is samilar to costom `View`,the main purpose is to add a constructor that takes a `Context` and `AttributeSet` as parameter, other code is emitted here, for more details,[click](https://github.com/Cricin/Folivora/blob/master/sample/src/main/java/cn/cricin/folivora/sample/drawable/WindmillDrawable.java) to view source code
3. use `WindmillDrawable` in your layout files,Folivora provided a `drawableName` attr,you can declare the drawable name here:
```xml
```
at runtime, the drawable is created by folivora and get worked:
you may ask, the drawable's name is to long to remember, it's difficult to write down,don't worry at it,folivora will gives the candidate of custom drawables if you typed down drawableName attr, attrs about the specific drawable is also will have code completion support.
> Support of custom drawables do not have the constructor which recieves `Context` and `AttributeSet` as parameter
Folivora take concerned it, source code of some drawables is not permited to modify, so,we provided a `DrawableFactory` interface,assume `WindmillDrawable` only have a constructor takes no parameter,but provided some methods to modify it, to support `WindmillDrawable`,we can do this:
```java
Folivora.addDrawableFactory(new Folivora.DrawableFactory() {
@Override
public Drawable newDrawable(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.WindmillDrawable);
WindmillDrawable d = new WindmillDrawable();
d.setColor0(a.getColor(R.styleable.WindmillDrawable_wdColor0, Color.BLACK));
d.setRotateDegrees(a.getInt(R.styleable.WindmillDrawable_wdRotateDegrees, 0));
...
a.recycle();
return d;
}
@Override
public Class extends Drawable> drawableClass() {
return WindmillDrawable.class;
}
});
```
> If you are using custom drawable,and your drawable contains other drawables, it is recommended to use `Folivora.getDrawable(Context ctx, TypedArray a, AttributeSet attrs, int attrIndex)` to get a drawable, this method will take care about nested shape creation, also you can do not follow this tip if you do not need nested shape support。
### Drawable caches
In previous releases,Folivora will create drawables according to attrs from view tag, a new instance is created for per view, which is waste resources, now Folivora supported drawable caching(LruCache,max = 128), usage is very simple,just add `app:drawableId` attr,set a id(string type,not android's id type) to drawable is ok。Folivora will lookup cache to find a cached drawable, which means,if in a layout.xml,a drawable should be referenced multi places, define it at first occurrence, then at other place, use the same `drawableId` to reference this drawable.
```xml
```
It is recommended to set `drawableId` to drawable which is reusable or inside a frequently used layout files, which makes a better performance.
### Download Sample APK
[Click to download](https://raw.githubusercontent.com/Cricin/Folivora/master/sample.apk)
### Design time preview
> preview result
after you added folivora in gradle and sync project,preview would been enabled by default, if unavailable, try to build your project.
### Attrs Reference
##### Common Attrs
attr | value| desc
---|--- | --- |
app:setAs|background(default) | src | foreground| set drawable as backgrond or src or foreground
app:drawableType|shape | layer_list | selector | ripple | clip | scale | animation | level_list|drawable type
app:drawableName|string|fq class name of custom drawable
app:drawableId|string|drawable unique id for cache use
##### Shape Attrs
attr | value | desc
---|--- | --- |
app:shapeType|rectangle(default)|oval|line|ring
app:shapeSolidSize|dimension
app:shapeSolidWidth|dimension
app:shapeSolidHeight|dimension
app:shapeSolidColor|color
app:shapeStokeWidth|dimension
app:shapeStokeDashWidth|dimension
app:shapeStokeDashGap|dimension
app:shapeCornerRadius|dimension
app:shapeCornerRadiusTopLeft|dimension
app:shapeCornerRadiusTopRight|dimension
app:shapeCornerRadiusBottomLeft|dimension
app:shapeCornerRadiusBottomRight|dimension
app:shapeGradientType|linear | radial | sweep
app:shapeGradientAngle|tb | tr_bl | rl | br_tl | bt | bl_tr | lr | tl_br|
app:shapeGradientStartColor|color
app:shapeGradientCenterColor|color
app:shapeGradientEndColor|color
app:shapeGradientRadius|dimension
app:shapeGradientCenterX|float(default 0.5)
app:shapeGradientCenterY|float(default 0.5)
##### Selector Attrs
attr | value| desc
---|--- | --- |
app:selectorStateFirst|reference | color|
app:selectorStateMiddle|reference | color|
app:selectorStateLast|reference | color|
app:selectorStateActive|reference | color|
app:selectorStateActivated|reference | color|
app:selectorStateAccelerate|reference | color|
app:selectorStateChecked|reference | color|
app:selectorStateCheckable|reference | color|
app:selectorStateEnabled|reference | color|
app:selectorStateFocused|reference | color|
app:selectorStatePressed|reference | color|
app:selectorStateNormal|reference | color|
##### LayerList Attrs
attr | value| desc
---|--- | --- |
app:layerItem0Drawable| reference | color| drawable innermost
app:layerItem0Insets|dimension|margin for drawable
app:layerItem0Left|dimension| left margin
app:layerItem0Right|dimension|right margin
app:layerItem0Top|dimension|top margin
app:layerItem0Bottom|dimension|bottom margin
...
layerlist supports at most 5 children drawables, just substitute the digit
##### Ripple Attrs
attr | value| desc
---|--- | --- |
app:rippleColor|color|ripple color when touched
app:rippleMask|reference | color|mask for ripple
app:rippleContent|reference | color|content for ripple
##### LevelList Attrs
attr | value| desc
---|--- | --- |
app:levelCurrentLevel|integer|current level
app:levelItem0Drawable|reference | color|drawable for item0
app:levelItem1MinLevel|integer|min level for item0
app:levelItem1MaxLevel|integer|max level for item0
...
levellist supports at most 5 children drawables, just substitute the digit
##### Clip Attrs
attr | value| desc
---|--- | --- |
app:clipDrawable|reference | color|drawable to be clipped
app:clipGravity|same as View's layout_gravity|gravity to clip
app:clipOrientation|vertical | horizontal|clip orientation
app:clipLevel|integer|current level(used to clip the drawable)
##### Scale Attrs
attr | value| desc
---|--- | --- |
app:scaleDrawable|reference | color|drawable to be scaled
app:scaleGravity|same as View's layout_gravity|gravity to scale
app:scaleWidth|float[0,1] or -1()|scale ratio for width
app:scaleHeight|float[0,1] or -1()|scale ratio for height
app:scaleLevel|integer[0,10000]|current level(used to scale the drawable)
##### Inset Attrs
attr | value| desc
---|--- | --- |
app:insetDrawable|reference | color|drawable to be inseted
app:insetAll|dimension|all inset
app:insetLeft|dimension|inset of left
app:insetTop|dimension|inset of top
app:insetRight|dimension|inset of right
app:insetBottom|dimension|inset of bottom
##### Animation Attrs
attr | value| desc
---|--- | --- |
app:animAutoPlay|boolean|play animation automaticly
app:animDuration|int(millisecond)|displayed duration per frame
app:animOneShot|boolean|play just once
app:animFrame0|reference | color|first frame's drawable
app:animDuration0|int(millisecond)|first frame displayed duration
animation supports at most 10 frames, just substitute the digit
## License
Copyright 2019 Cricin
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: android_release_aar.gradle
================================================
// ./gradlew clean build generateRelease
apply plugin: 'maven'
def groupId = project.PUBLISH_GROUP_ID
def artifactId = project.PUBLISH_ARTIFACT_ID
def version = project.PUBLISH_VERSION
def localReleaseDest = "${buildDir}/release/${version}"
task androidJavadocs(type: Javadoc) {
failOnError = false
source = android.sourceSets.main.java.srcDirs
ext.androidJar = "${android.sdkDirectory}/platforms/${android.compileSdkVersion}/android.jar"
classpath += files(ext.androidJar)
}
task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {
classifier = 'javadoc'
from androidJavadocs.destinationDir
}
task androidSourcesJar(type: Jar) {
classifier = 'sources'
from android.sourceSets.main.java.srcDirs
}
uploadArchives {
repositories.mavenDeployer {
pom.groupId = groupId
pom.artifactId = artifactId
pom.version = version
// Add other pom properties here if you want (developer details / licenses)
repository(url: "file://${localReleaseDest}")
}
}
task zipRelease(type: Zip) {
from localReleaseDest
destinationDir buildDir
archiveName "release-${version}.zip"
}
task generateRelease {
doLast {
println "Release ${version} can be found at ${localReleaseDest}/"
println "Release ${version} zipped can be found ${buildDir}/release-${version}.zip"
}
}
generateRelease.dependsOn(uploadArchives)
generateRelease.dependsOn(zipRelease)
artifacts {
archives androidSourcesJar
archives androidJavadocsJar
}
================================================
FILE: build.gradle
================================================
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
================================================
FILE: folivora/build.gradle
================================================
apply plugin: 'com.android.library'
def verName = '0.1.0'
android {
compileSdkVersion 29
defaultConfig {
minSdkVersion 16
targetSdkVersion 29
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
lintChecks project(':lint')
lintPublish project(':lint')
}
ext {
PUBLISH_GROUP_ID = 'cn.cricin'
PUBLISH_ARTIFACT_ID = 'folivora'
PUBLISH_VERSION = verName
}
apply from: rootProject.file('android_release_aar.gradle')
================================================
FILE: folivora/src/main/AndroidManifest.xml
================================================
================================================
FILE: folivora/src/main/java/cn/cricin/folivora/DrawableParser.java
================================================
/*
* Copyright (C) 2019 Cricin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.cricin.folivora;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.InsetDrawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.LevelListDrawable;
import android.graphics.drawable.RippleDrawable;
import android.graphics.drawable.ScaleDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.util.StateSet;
import android.view.Gravity;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static cn.cricin.folivora.Folivora.TAG;
import static cn.cricin.folivora.Folivora.getDrawable;
/**
* A DrawableParser take responsibility of drawable parsing, Folivora
* will find best match DrawableParser to parse a drawable instance
* for view. each subclass handles one or more drawable parsing when
* a view want a drawable to decorate self.
*/
public interface DrawableParser {
/**
* Entry point for subclass to accomplish drawable parsing task
* @param request current parsing request
* @return a parsed drawable instance, or null
*/
Drawable parse(ParseRequest request);
/**
* Create a new GradientDrawable(shape).
* attrs:
*
* app:layerItem4Drawable drawable
* app:layerItem4Insets dimension
* app:layerItem4Left dimension
* app:layerItem4Top dimension
* app:layerItem4Right dimension
* app:layerItem4Bottom dimension
*/
class LayerDrawableParser implements DrawableParser {
@Override
public Drawable parse(ParseRequest request) {
final Context ctx = request.context();
final AttributeSet attrs = request.attrs();
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.Folivora_Layer);
List childDrawables = new ArrayList<>(5);
List childInsets = new ArrayList<>(5);
Drawable temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Layer_layerItem0Drawable);
if (temp != null) {
childDrawables.add(temp);
int insets = a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem0Insets, 0);
childInsets.add(new Rect(
a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem0Left, insets),
a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem0Top, insets),
a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem0Right, insets),
a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem0Bottom, insets)
));
}
temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Layer_layerItem1Drawable);
if (temp != null) {
childDrawables.add(temp);
int insets = a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem1Insets, 0);
childInsets.add(new Rect(
a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem1Left, insets),
a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem1Top, insets),
a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem1Right, insets),
a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem1Bottom, insets)
));
}
temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Layer_layerItem2Drawable);
if (temp != null) {
childDrawables.add(temp);
int insets = a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem2Insets, 0);
childInsets.add(new Rect(
a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem2Left, insets),
a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem2Top, insets),
a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem2Right, insets),
a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem2Bottom, insets)
));
}
temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Layer_layerItem3Drawable);
if (temp != null) {
childDrawables.add(temp);
int insets = a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem3Insets, 0);
childInsets.add(new Rect(
a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem3Left, insets),
a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem3Top, insets),
a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem3Right, insets),
a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem3Bottom, insets)
));
}
temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Layer_layerItem4Drawable);
if (temp != null) {
childDrawables.add(temp);
int insets = a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem4Insets, 0);
childInsets.add(new Rect(
a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem4Left, insets),
a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem4Top, insets),
a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem4Right, insets),
a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem4Bottom, insets)
));
}
a.recycle();
LayerDrawable d = new LayerDrawable(childDrawables.toArray(new Drawable[0]));
for (int i = 0; i < childInsets.size(); i++) {
Rect inset = childInsets.get(i);
d.setLayerInset(i, inset.left, inset.top, inset.right, inset.bottom);
}
return d;
}
}
/**
* Create a new RippleDrawable, if current platform does not support,
* we will try to create a substitute from {@link RippleFallback} rippleFallback.
* attrs:
*
* app:rippleColor color
* app:rippleContent drawable
* app:rippleMask drawable
*/
class RippleDrawableParser implements DrawableParser {
@Override
public Drawable parse(ParseRequest request) {
final Context ctx = request.context();
final AttributeSet attrs = request.attrs();
final RippleFallback fallback = request.rippleFallback();
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.Folivora_Ripple);
ColorStateList color;
Drawable content;
Drawable mask;
try {
color = a.getColorStateList(R.styleable.Folivora_Ripple_rippleColor);
if (color == null) {
throw new IllegalStateException("rippleColor not set");
}
content = getDrawable(ctx, a, attrs, R.styleable.Folivora_Ripple_rippleContent);
mask = getDrawable(ctx, a, attrs, R.styleable.Folivora_Ripple_rippleMask);
} finally {
a.recycle();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return new RippleDrawable(color, content, mask);
} else if (fallback != null) {
return fallback.onFallback(color, content, mask, ctx);
} else {
Log.w(TAG, "RippleDrawable is not available in current platform");
return null;
}
}
}
/**
* Create a new LevelListDrawable, currently we only support 5 children drawables.
* attrs:
*
* app:levelCurrentLevel int
* app:levelItem0Drawable drawable
* app:levelItem0MinLevel int
* app:levelItem0MaxLevel int
* app:levelItem1Drawable drawable
* app:levelItem1MinLevel int
* app:levelItem1MaxLevel int
* app:levelItem2Drawable drawable
* app:levelItem2MinLevel int
* app:levelItem2MaxLevel int
* app:levelItem3Drawable drawable
* app:levelItem3MinLevel int
* app:levelItem3MaxLevel int
* app:levelItem4Drawable drawable
* app:levelItem4MinLevel int
* app:levelItem4MaxLevel int
*/
class LevelListDrawableParser implements DrawableParser {
@Override
public Drawable parse(ParseRequest request) {
final Context ctx = request.context();
final AttributeSet attrs = request.attrs();
LevelListDrawable lld = new LevelListDrawable();
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.Folivora_Level);
if (a.hasValue(R.styleable.Folivora_Level_levelItem0Drawable)) {
lld.addLevel(
a.getInt(R.styleable.Folivora_Level_levelItem0MinLevel, 0),
a.getInt(R.styleable.Folivora_Level_levelItem0MaxLevel, 0),
getDrawable(ctx, a, attrs, R.styleable.Folivora_Level_levelItem0Drawable)
);
}
if (a.hasValue(R.styleable.Folivora_Level_levelItem1Drawable)) {
lld.addLevel(
a.getInt(R.styleable.Folivora_Level_levelItem1MinLevel, 0),
a.getInt(R.styleable.Folivora_Level_levelItem1MaxLevel, 0),
getDrawable(ctx, a, attrs, R.styleable.Folivora_Level_levelItem1Drawable)
);
}
if (a.hasValue(R.styleable.Folivora_Level_levelItem2Drawable)) {
lld.addLevel(
a.getInt(R.styleable.Folivora_Level_levelItem2MinLevel, 0),
a.getInt(R.styleable.Folivora_Level_levelItem2MaxLevel, 0),
getDrawable(ctx, a, attrs, R.styleable.Folivora_Level_levelItem2Drawable)
);
}
if (a.hasValue(R.styleable.Folivora_Level_levelItem3Drawable)) {
lld.addLevel(
a.getInt(R.styleable.Folivora_Level_levelItem3MinLevel, 0),
a.getInt(R.styleable.Folivora_Level_levelItem3MaxLevel, 0),
getDrawable(ctx, a, attrs, R.styleable.Folivora_Level_levelItem3Drawable)
);
}
if (a.hasValue(R.styleable.Folivora_Level_levelItem4Drawable)) {
lld.addLevel(
a.getInt(R.styleable.Folivora_Level_levelItem4MinLevel, 0),
a.getInt(R.styleable.Folivora_Level_levelItem4MaxLevel, 0),
getDrawable(ctx, a, attrs, R.styleable.Folivora_Level_levelItem4Drawable)
);
}
lld.setLevel(a.getInt(R.styleable.Folivora_Level_levelCurrentLevel, 0));
a.recycle();
return lld;
}
}
/**
* Create a new ClipDrawable.
* attrs:
*
* app:clipDrawable drawable
* app:clipGravity enum
* app:clipOrientation enum
* app:clipLevel int(10000 means no clip)
*/
class ClipDrawableParser implements DrawableParser {
@Override
public Drawable parse(ParseRequest request) {
final Context ctx = request.context();
final AttributeSet attrs = request.attrs();
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.Folivora_Clip);
final Drawable child = getDrawable(ctx, a, attrs, R.styleable.Folivora_Clip_clipDrawable);
final int clipGravity = a.getInt(R.styleable.Folivora_Clip_clipGravity, Gravity.START);
final int clipOrientation = a.getInt(R.styleable.Folivora_Clip_clipOrientation, ClipDrawable.HORIZONTAL);
ClipDrawable cd = new ClipDrawable(child, clipGravity, clipOrientation);
cd.setLevel(a.getInt(R.styleable.Folivora_Clip_clipLevel, 10000/*no clip*/));
a.recycle();
return cd;
}
}
/**
* Create a new InsetDrawable, inset by fraction is not support, since it is an new api.
* attrs:
*
* app:insetDrawable drawable
* app:insetAll dimension
* app:insetLeft dimension
* app:insetTop dimension
* app:insetRight dimension
* app:insetBottom dimension
*/
class InsetDrawableParser implements DrawableParser {
@Override
public Drawable parse(ParseRequest request) {
final Context ctx = request.context();
final AttributeSet attrs = request.attrs();
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.Folivora_Inset);
int insetAll = a.getDimensionPixelSize(R.styleable.Folivora_Inset_insetAll, 0);
int[] ints = {
R.styleable.Folivora_Inset_insetLeft,
R.styleable.Folivora_Inset_insetTop,
R.styleable.Folivora_Inset_insetRight,
R.styleable.Folivora_Inset_insetBottom
};
for (int i = 0; i < ints.length; i++) {
ints[i] = a.getDimensionPixelSize(ints[i], insetAll);
}
final Drawable child = getDrawable(ctx, a, attrs, R.styleable.Folivora_Inset_insetDrawable);
a.recycle();
return new InsetDrawable(child, ints[0], ints[1], ints[2], ints[3]);
}
}
/**
* Create a new ScaleDrawable.
* attrs:
*
* app:scaleDrawable drawable
* app:scaleGravity enum
* app:scaleWidth float
* app:scaleHeight float
* app:scaleLevel int
*/
class ScaleDrawableParser implements DrawableParser {
@Override
public Drawable parse(ParseRequest request) {
final Context ctx = request.context();
final AttributeSet attrs = request.attrs();
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.Folivora_Scale);
ScaleDrawable sd = new ScaleDrawable(
getDrawable(ctx, a, attrs, R.styleable.Folivora_Scale_scaleDrawable),
a.getInt(R.styleable.Folivora_Scale_scaleGravity, Gravity.START),
a.getFloat(R.styleable.Folivora_Scale_scaleWidth, -1F),
a.getFloat(R.styleable.Folivora_Scale_scaleHeight, -1F)
);
sd.setLevel(a.getInt(R.styleable.Folivora_Scale_scaleLevel, 1));
a.recycle();
return sd;
}
}
/**
* Create a new AnimationDrawable, currently we only support 10 frames.
* attrs:
*
* app:animFrame0 drawable
* app:animDuration0 int(millisecond)
* app:animFrame1 drawable
* app:animDuration1 int(millisecond)
* app:animFrame2 drawable
* app:animDuration2 int(millisecond)
* app:animFrame3 drawable
* app:animDuration3 int(millisecond)
* app:animFrame4 drawable
* app:animDuration4 int(millisecond)
* app:animFrame5 drawable
* app:animDuration5 int(millisecond)
* app:animFrame6 drawable
* app:animDuration6 int(millisecond)
* app:animFrame7 drawable
* app:animDuration7 int(millisecond)
* app:animFrame8 drawable
* app:animDuration8 int(millisecond)
* app:animFrame9 drawable
* app:animDuration9 int(millisecond)
*/
class AnimationDrawableParser implements DrawableParser {
@SuppressWarnings("ConstantConditions")
@Override
public Drawable parse(ParseRequest request) {
final Context ctx = request.context();
final AttributeSet attrs = request.attrs();
AnimationDrawable ad;
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.Folivora_Animation);
final boolean autoPlay = a.getBoolean(R.styleable.Folivora_Animation_animAutoPlay, false);
if (autoPlay) {
// Workaround for android bug, animation drawable does not played
// normally when calling start() on activity's onCreate() method.
ad = new AnimationDrawable() {
boolean autoPlayed;
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
if (!autoPlayed) {
if (isOneShot()) {
Log.i(TAG, "Auto play and oneshot both enabled, you could not see the animation");
}
this.start();
autoPlayed = true;
}
}
};
} else {
ad = new AnimationDrawable();
}
ad.setOneShot(a.getBoolean(R.styleable.Folivora_Animation_animOneShot, false));
final int frameDuration = a.getInt(R.styleable.Folivora_Animation_animDuration, -1);
if (a.hasValue(R.styleable.Folivora_Animation_animFrame0)) {
ad.addFrame(a.getDrawable(R.styleable.Folivora_Animation_animFrame0),
a.getInt(R.styleable.Folivora_Animation_animDuration0, frameDuration));
}
if (a.hasValue(R.styleable.Folivora_Animation_animFrame1)) {
ad.addFrame(a.getDrawable(R.styleable.Folivora_Animation_animFrame1),
a.getInt(R.styleable.Folivora_Animation_animDuration1, frameDuration));
}
if (a.hasValue(R.styleable.Folivora_Animation_animFrame2)) {
ad.addFrame(a.getDrawable(R.styleable.Folivora_Animation_animFrame2),
a.getInt(R.styleable.Folivora_Animation_animDuration2, frameDuration));
}
if (a.hasValue(R.styleable.Folivora_Animation_animFrame3)) {
ad.addFrame(a.getDrawable(R.styleable.Folivora_Animation_animFrame3),
a.getInt(R.styleable.Folivora_Animation_animDuration3, frameDuration));
}
if (a.hasValue(R.styleable.Folivora_Animation_animFrame4)) {
ad.addFrame(a.getDrawable(R.styleable.Folivora_Animation_animFrame4),
a.getInt(R.styleable.Folivora_Animation_animDuration4, frameDuration));
}
if (a.hasValue(R.styleable.Folivora_Animation_animFrame5)) {
ad.addFrame(a.getDrawable(R.styleable.Folivora_Animation_animFrame5),
a.getInt(R.styleable.Folivora_Animation_animDuration5, frameDuration));
}
if (a.hasValue(R.styleable.Folivora_Animation_animFrame6)) {
ad.addFrame(a.getDrawable(R.styleable.Folivora_Animation_animFrame6),
a.getInt(R.styleable.Folivora_Animation_animDuration6, frameDuration));
}
if (a.hasValue(R.styleable.Folivora_Animation_animFrame7)) {
ad.addFrame(a.getDrawable(R.styleable.Folivora_Animation_animFrame7),
a.getInt(R.styleable.Folivora_Animation_animDuration7, frameDuration));
}
if (a.hasValue(R.styleable.Folivora_Animation_animFrame8)) {
ad.addFrame(a.getDrawable(R.styleable.Folivora_Animation_animFrame8),
a.getInt(R.styleable.Folivora_Animation_animDuration8, frameDuration));
}
if (a.hasValue(R.styleable.Folivora_Animation_animFrame9)) {
ad.addFrame(a.getDrawable(R.styleable.Folivora_Animation_animFrame9),
a.getInt(R.styleable.Folivora_Animation_animDuration9, frameDuration));
}
a.recycle();
return ad;
}
}
/**
* Try to create a custom drawable from the given class name, note
* that the custom drawable class must have a public constructor
* that takes a {@link Context} context and a {@link AttributeSet}
* attrs as parameters
*/
class ReflectiveDrawableParser implements DrawableParser {
// Stuffs for create custom drawable reflectively
private static Set sFailedNames = new HashSet<>();
private static Class[] sConstructorSignature = {Context.class, AttributeSet.class};
private static Object[] sConstructorArgs = new Object[2];
private static Map> sConstructorCache = new HashMap<>();
@Override
public Drawable parse(ParseRequest request) {
final Context ctx = request.context();
final AttributeSet attrs = request.attrs();
final String drawableName = request.drawableClassName();
if (sFailedNames.contains(drawableName)) return null;
if (drawableName.indexOf('.') == -1) return null;
Constructor extends Drawable> constructor = sConstructorCache.get(drawableName);
try {
if (constructor == null) {
Class extends Drawable> clazz = ctx.getClassLoader().loadClass(drawableName)
.asSubclass(Drawable.class);
constructor = clazz.getConstructor(sConstructorSignature);
constructor.setAccessible(true);
sConstructorCache.put(drawableName, constructor);
}
sConstructorArgs[0] = ctx;
sConstructorArgs[1] = attrs;
return constructor.newInstance(sConstructorArgs);
} catch (ClassNotFoundException cnfe) {
sFailedNames.add(drawableName);
Log.w(TAG, "drawable class [" + drawableName
+ "] not found, Folivora will never try to load it any more");
} catch (NoSuchMethodException nsme) {
sFailedNames.add(drawableName);
final String classSimpleName = drawableName.substring(drawableName.lastIndexOf('.') + 1);
final String msg = "constructor " + classSimpleName + "(Context context, AttributeSet attrs)"
+ " does not exists in drawable class [" + drawableName + "], Folivora will never try to" +
" load it any more";
Log.w(TAG, msg);
} catch (IllegalAccessException iae) {
throw new AssertionError(iae);//never happen
} catch (Exception e) {
Log.w(TAG, "exception occurred instantiating drawable [" + drawableName + "]", e);
} finally {
sConstructorArgs[0] = null;
sConstructorArgs[1] = null;
}
return null;
}
}
}
================================================
FILE: folivora/src/main/java/cn/cricin/folivora/Folivora.java
================================================
/*
* Copyright (C) 2019 Cricin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.cricin.folivora;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.RippleDrawable;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.util.LruCache;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Folivora support sets drawable directly in your layout.xml files, no need
* to create XXX.xml in drawable directory. just write down attributes we
* provided in your layout.xml, folivora will take care of with this attrs
* and create suitable drawable's for view.
*
* Folivora is light weight, you would use {@link #wrap(Context)} wrap()
* or {@link #installViewFactory(Context)} installViewFactory() to enable
* folivora functions
*
* @see #wrap(Context)
* @see #installViewFactory(Context)
* @see #setRippleFallback(RippleFallback)
* @see #getDrawable(Context, TypedArray, AttributeSet, int)
* @see #addOnViewCreatedListener(OnViewCreatedListener)
*/
public final class Folivora {
static final String TAG = "Folivora";
// Drawable type enums, keep sync with app:drawableType
private static final int DRAWABLE_TYPE_SHAPE = 0;
private static final int DRAWABLE_TYPE_SELECTOR = 1;
private static final int DRAWABLE_TYPE_LAYER = 2;
private static final int DRAWABLE_TYPE_RIPPLE = 3;
private static final int DRAWABLE_TYPE_LEVEL = 4;
private static final int DRAWABLE_TYPE_CLIP = 5;
private static final int DRAWABLE_TYPE_INSET = 6;
private static final int DRAWABLE_TYPE_SCALE = 7;
private static final int DRAWABLE_TYPE_ANIMATION = 8;
// Set as enums, keep sync with app:setAs
private static final int SET_AS_BACKGROUND = 0;
private static final int SET_AS_SRC = 1;
private static final int SET_AS_FOREGROUND = 2;
// Exposed apis
private static RippleFallback sRippleFallback;
private static List sOnViewCreatedListeners;
private static Map sDrawableParsers = new HashMap<>();
private static DrawableParser sReflectiveDrawableParser = new DrawableParser.ReflectiveDrawableParser();
private static SparseArray sSystemDrawableNames = new SparseArray<>();
static {
sDrawableParsers.put("android.graphics.drawable.GradientDrawable", new DrawableParser.GradientDrawableParser());
sDrawableParsers.put("android.graphics.drawable.StateListDrawable", new DrawableParser.StateListDrawableParser());
sDrawableParsers.put("android.graphics.drawable.LayerDrawable", new DrawableParser.LayerDrawableParser());
sDrawableParsers.put("android.graphics.drawable.RippleDrawable", new DrawableParser.RippleDrawableParser());
sDrawableParsers.put("android.graphics.drawable.LevelListDrawable", new DrawableParser.LevelListDrawableParser());
sDrawableParsers.put("android.graphics.drawable.ClipDrawable", new DrawableParser.ClipDrawableParser());
sDrawableParsers.put("android.graphics.drawable.InsetDrawable", new DrawableParser.InsetDrawableParser());
sDrawableParsers.put("android.graphics.drawable.ScaleDrawable", new DrawableParser.ScaleDrawableParser());
sDrawableParsers.put("android.graphics.drawable.AnimationDrawable", new DrawableParser.AnimationDrawableParser());
sSystemDrawableNames.put(DRAWABLE_TYPE_SHAPE, "android.graphics.drawable.GradientDrawable");
sSystemDrawableNames.put(DRAWABLE_TYPE_SELECTOR, "android.graphics.drawable.StateListDrawable");
sSystemDrawableNames.put(DRAWABLE_TYPE_LAYER, "android.graphics.drawable.LayerDrawable");
sSystemDrawableNames.put(DRAWABLE_TYPE_RIPPLE, "android.graphics.drawable.RippleDrawable");
sSystemDrawableNames.put(DRAWABLE_TYPE_LEVEL, "android.graphics.drawable.LevelListDrawable");
sSystemDrawableNames.put(DRAWABLE_TYPE_CLIP, "android.graphics.drawable.ClipDrawable");
sSystemDrawableNames.put(DRAWABLE_TYPE_INSET, "android.graphics.drawable.InsetDrawable");
sSystemDrawableNames.put(DRAWABLE_TYPE_SCALE, "android.graphics.drawable.ScaleDrawable");
sSystemDrawableNames.put(DRAWABLE_TYPE_ANIMATION, "android.graphics.drawable.AnimationDrawable");
}
// Cached drawables with it's ids
private static LruCache sDrawableCache = new LruCache<>(128);
// Cache is enabled at runtime, but at design time, this should be disabled for work properly
@SuppressWarnings("FieldCanBeLocal") // This is accessed by layout editor
private static boolean sDrawableCacheEnabled = true;
/**
* Try to get a child drawable, if the attrIndex pointing to a specific drawable,
* then load it in normal way, if the attrIndex pointing a enum(shape index), try
* to create it from the given attrs
*
* @param ctx current context
* @param a caller's typed array
* @param attrs attributes from view tag
* @param attrIndex attribute index in the typed array
* @return a drawable, or a newly created GradientDrawable from attrs, or null
*/
@SuppressWarnings("WeakerAccess")
public static Drawable getDrawable(Context ctx, TypedArray a, AttributeSet attrs, int attrIndex) {
if (!a.hasValue(attrIndex)) return null;
Drawable result = null;
ShapeAttrs shapeAttrs = ShapeAttrs.forIndex(a.getInt(attrIndex, -1));
if (shapeAttrs != null) {
final String className = "android.graphics.drawable.GradientDrawable";
DrawableParser parser = sDrawableParsers.get(className);
ParseRequest request = new ParseRequest(ctx, attrs, sRippleFallback, shapeAttrs, className);
if (parser != null) {
result = parser.parse(request);
}
}
if (result == null) {
result = a.getDrawable(attrIndex);
}
return result;
}
/**
* Create a drawable to the specific view with attrs, this method is
* used by folivora internally, but in order to support preview for
* the views folivora not stubbed, this method becomes publicly
*
* @param view view of drawable attached
* @param attrs attributes from view tag
*/
static void applyDrawableToView(View view, AttributeSet attrs) {
final Context ctx = view.getContext();
// Step1 extract attrs
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.Folivora);
int drawableType = a.getInt(R.styleable.Folivora_drawableType, -1);
String drawableId = a.getString(R.styleable.Folivora_drawableId);
String drawableName = a.getString(R.styleable.Folivora_drawableName);
int setAs = a.getInt(R.styleable.Folivora_setAs, SET_AS_BACKGROUND);
a.recycle();
if (drawableType < 0 && drawableId == null && drawableName == null) return;
// Step2 lookup cached if available
Drawable cached = null;
Drawable d = null;
if (drawableId != null) {
cached = sDrawableCache.get(drawableId);
if (cached != null && cached.getConstantState() != null) {
cached = cached.getConstantState().newDrawable();
}
}
// Step3 try to create a new drawable and cached it
if (!sDrawableCacheEnabled || cached == null) {
d = createDrawable(ctx, attrs, drawableType, drawableName);
if (d != null && d.getConstantState() != null && drawableId != null) {
sDrawableCache.put(drawableId, d);
}
}
d = d == null ? cached : d;
if (d == null) return;
// Step4 set drawable to view
if (setAs == SET_AS_BACKGROUND) {
view.setBackground(d);
} else if (setAs == SET_AS_SRC && view instanceof ImageView) {
((ImageView) view).setImageDrawable(d);
} else if (setAs == SET_AS_FOREGROUND) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
view.setForeground(d);
} else if (view instanceof FrameLayout) {
//noinspection RedundantCast
((FrameLayout) view).setForeground(d);
} else {
Log.w(TAG, "Folivora can not set foreground to [" + view.getClass()
+ "], Current device platform is lower than MarshMallow");
}
}
}
private static Drawable createDrawable(Context ctx, AttributeSet attrs, int drawableType, String drawableName) {
String realDrawableName = null;
if (drawableType >= 0) {
realDrawableName = sSystemDrawableNames.get(drawableType);
}
if (realDrawableName == null) {
realDrawableName = drawableName;
}
if (realDrawableName == null) return null;
DrawableParser parser = sDrawableParsers.get(realDrawableName);
if (parser == null && !realDrawableName.startsWith("android.graphics.drawable")) {
parser = sReflectiveDrawableParser;
}
if (parser == null) return null;
ParseRequest request = new ParseRequest(ctx, attrs, sRippleFallback, ShapeAttrs.forIndex(0), realDrawableName);
return parser.parse(request);
}
/**
* Install Folivora's ViewFactory to current context. note that if
* you are using AppCompatActivity, this method should called after
* your activity's super.onCreate() method, since AppCompatDelegate
* will install a {@link LayoutInflater.Factory2} factory2 to this
* context.
*
* @param ctx context to enable folivora support
*/
public static void installViewFactory(Context ctx) {
LayoutInflater inflater = LayoutInflater.from(ctx);
LayoutInflater.Factory2 factory2 = inflater.getFactory2();
if (factory2 instanceof FolivoraViewFactory) return;
FolivoraViewFactory viewFactory = new FolivoraViewFactory();
viewFactory.mFactory2 = factory2;
if (factory2 != null) {
FolivoraViewFactory.forceSetFactory2(inflater, viewFactory);
} else {
inflater.setFactory2(viewFactory);
}
}
/**
* Wraps the given context, replace the {@link LayoutInflater} inflater
* to folivora's implementation, this method does nothing if the given
* context is already been wrapped.
*
* @param newBase new base context
* @return a wrapped context
*/
public static Context wrap(final Context newBase) {
final LayoutInflater inflater = LayoutInflater.from(newBase);
if (inflater instanceof FolivoraInflater) return newBase;
return new ContextWrapper(newBase) {
private FolivoraInflater mInflater;
@Override
public Object getSystemService(String name) {
if (LAYOUT_INFLATER_SERVICE.equals(name)) {
if (mInflater == null) {
mInflater = new FolivoraInflater(newBase, inflater);
}
return mInflater;
}
return super.getSystemService(name);
}
};
}
/**
* Set a fallback to create substitute drawable when the {@link RippleDrawable}
* RippleDrawable is not available in current device.
*
* @param fallback a fallback to create drawable
*/
public static void setRippleFallback(RippleFallback fallback) {
sRippleFallback = fallback;
}
public static void registerDrawableParser(Class extends Drawable> drawableClass, DrawableParser parser) {
final String className = drawableClass.getCanonicalName();
sDrawableParsers.put(className, parser);
}
/**
* Add a {@link OnViewCreatedListener} listener to folivora, folivora
* will notify these listeners when a view is created. this listener
* allows you do some extra customization about the inflated views.
*
* @param l listener to register
*/
public static void addOnViewCreatedListener(OnViewCreatedListener l) {
if (sOnViewCreatedListeners == null) {
sOnViewCreatedListeners = new ArrayList<>();
}
sOnViewCreatedListeners.add(l);
}
static void dispatchViewCreated(View view, AttributeSet attrs) {
if (sOnViewCreatedListeners != null) {
for (OnViewCreatedListener l : sOnViewCreatedListeners) {
l.onViewCreated(view, attrs);
}
}
}
private Folivora() {}
}
================================================
FILE: folivora/src/main/java/cn/cricin/folivora/FolivoraInflater.java
================================================
/*
* Copyright (C) 2019 Cricin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.cricin.folivora;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import org.xmlpull.v1.XmlPullParser;
/**
* A LayoutInflater implementation which delegate all view creation
* to {@link FolivoraViewFactory}.
*/
final class FolivoraInflater extends LayoutInflater {
private static final String[] sClassPrefixList = {
"android.widget.",
"android.webkit.",
"android.app."
};
FolivoraInflater(Context newContext, LayoutInflater original) {
super(original, newContext);
}
@Override
public LayoutInflater cloneInContext(Context newContext) {
return new FolivoraInflater(newContext, this);
}
@Override
public void setFactory(Factory factory) {
FolivoraViewFactory f = (FolivoraViewFactory) getFactory2();
if (f == null) {
super.setFactory2(f = new FolivoraViewFactory());
}
f.mFactory = factory;
}
@Override
public void setFactory2(Factory2 factory2) {
FolivoraViewFactory f = (FolivoraViewFactory) getFactory2();
if (f == null) {
super.setFactory2(f = new FolivoraViewFactory());
}
f.mFactory2 = factory2;
}
@Override
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
Factory2 factory2 = getFactory2();
if (factory2 == null) {
super.setFactory2(new FolivoraViewFactory());
}
return super.inflate(parser, root, attachToRoot);
}
/** fallback if FolivoraViewFactory could not create views properly */
@Override
protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
for (String prefix : sClassPrefixList) {
try {
View view = createView(name, prefix, attrs);
if (view != null) {
return view;
}
} catch (ClassNotFoundException e) {
// In this case we want to let the base class take a crack
// at it.
}
}
return super.onCreateView(name, attrs);
}
}
================================================
FILE: folivora/src/main/java/cn/cricin/folivora/FolivoraViewFactory.java
================================================
/*
* Copyright (C) 2019 Cricin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.cricin.folivora;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
/**
* A view factory takes responsibility of view creation, if the view
* is created, folivora will create a drawable for it if available.
*/
final class FolivoraViewFactory implements LayoutInflater.Factory2 {
private static final String[] sClassPrefixList = {
"android.widget.",
"android.webkit.",
"android.app.",
"android.view."
};
private static final Class>[] sConstructorSignature = new Class[]{
Context.class, AttributeSet.class};
private static Object[] sConstructorArgs = new Object[2];
private static Map> sConstructorMap = new HashMap<>();
LayoutInflater.Factory2 mFactory2;
LayoutInflater.Factory mFactory;
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
return onCreateView(null, name, context, attrs);
}
@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
View view = null;
if (mFactory2 != null) {
view = mFactory2.onCreateView(parent, name, context, attrs);
}
if (view == null && mFactory != null) {
view = mFactory.onCreateView(name, context, attrs);
}
if (view == null && name.endsWith("ViewStub")) return null;//fix NPE when creating ViewStub
if (view == null && name.indexOf('.') != -1) {
view = createView(name, context, attrs);
}
if (view == null) {
for (String prefix : sClassPrefixList) {
view = createView(prefix + name, context, attrs);
if (view != null) break;
}
}
if (view != null) {
Folivora.applyDrawableToView(view, attrs);
Folivora.dispatchViewCreated(view, attrs);
}
return view;
}
private static View createView(String name, Context ctx, AttributeSet attrs) {
Constructor extends View> constructor = sConstructorMap.get(name);
try {
if (constructor == null) {
// Class not found in the cache, see if it's real, and try to add it
Class extends View> clazz = ctx.getClassLoader().loadClass(name).asSubclass(View.class);
constructor = clazz.getConstructor(sConstructorSignature);
sConstructorMap.put(name, constructor);
}
constructor.setAccessible(true);
sConstructorArgs[0] = ctx;
sConstructorArgs[1] = attrs;
return constructor.newInstance(sConstructorArgs);
} catch (Exception e) {
// We do not want to catch these, lets return null and let the actual LayoutInflater
// try
return null;
} finally {
sConstructorArgs[0] = null;
sConstructorArgs[1] = null;
}
}
private static LayoutInflater getLayoutInflater(Context context) {
return LayoutInflater.from(context);
}
private static boolean sCheckedField;
private static Field sLayoutInflaterFactory2Field;
static void forceSetFactory2(LayoutInflater inflater, LayoutInflater.Factory2 factory) {
if (!sCheckedField) {
try {
//noinspection JavaReflectionMemberAccess
sLayoutInflaterFactory2Field = LayoutInflater.class.getDeclaredField("mFactory2");
sLayoutInflaterFactory2Field.setAccessible(true);
} catch (NoSuchFieldException e) {
Log.e(Folivora.TAG, "forceSetFactory2 Could not find field 'mFactory2' on class "
+ inflater.getClass().getName() + "; Folivora will not available.", e);
}
sCheckedField = true;
}
if (sLayoutInflaterFactory2Field != null) {
try {
sLayoutInflaterFactory2Field.set(inflater, factory);
} catch (Exception e) {
Log.e(Folivora.TAG, "forceSetFactory2 could not set the Factory2 on LayoutInflater "
+ inflater + "; Folivora will not available.", e);
}
}
}
}
================================================
FILE: folivora/src/main/java/cn/cricin/folivora/OnViewCreatedListener.java
================================================
/*
* Copyright (C) 2019 Cricin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.cricin.folivora;
import android.util.AttributeSet;
import android.view.View;
/**
* A listener notified when a view is been created. you can
* do some customization on the view based on the attrs. eg,
* change text or typeface of TextView or change src of ImageView
*/
public interface OnViewCreatedListener {
void onViewCreated(View view, AttributeSet attrs);
}
================================================
FILE: folivora/src/main/java/cn/cricin/folivora/ParseRequest.java
================================================
/*
* Copyright (C) 2019 Cricin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.cricin.folivora;
import android.content.Context;
import android.util.AttributeSet;
/**
* A ParseRequest holding all information of drawable parsing task
* each field may be used by different DrawableParsers.
*/
public final class ParseRequest {
private final Context mContext;
private final AttributeSet mAttrs;
private final RippleFallback mRippleFallback;
private final ShapeAttrs mShapeAttrs;
private final String mDrawableClassName;
/*package*/ParseRequest(Context context,
AttributeSet attrs,
RippleFallback fallback,
ShapeAttrs shapeAttrs,
String drawableClassName) {
this.mContext = context;
this.mAttrs = attrs;
this.mRippleFallback = fallback;
this.mShapeAttrs = shapeAttrs;
this.mDrawableClassName = drawableClassName;
}
/**
* @return current inflation context
*/
public Context context() {
return mContext;
}
/**
* @return attribute retrieved from view tag
*/
public AttributeSet attrs() {
return mAttrs;
}
/**
* @return a fallback for RippleDrawable
*/
public RippleFallback rippleFallback() {
return mRippleFallback;
}
/**
* @return attribute information of a shape at different indexes, used by GradientDrawableParser
*/
public ShapeAttrs shapeAttrs() {
return mShapeAttrs;
}
/**
* @return full qualified class name of drawable to be inflated
*/
public String drawableClassName() {
return mDrawableClassName;
}
}
================================================
FILE: folivora/src/main/java/cn/cricin/folivora/RippleFallback.java
================================================
/*
* Copyright (C) 2019 Cricin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.cricin.folivora;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.drawable.Drawable;
import android.os.Build;
/**
* This class is designed for device platform lowers than
* {@link Build.VERSION_CODES#LOLLIPOP} lollipop, which RippleDrawable
* is unavailable, you can create substitution drawable here
*/
public interface RippleFallback {
/**
* Called when the view want a RippleDrawable, but it is unavailable in
* current device
*
* @param color ripple color, nonnull
* @param content content of ripple, nullable
* @param mask ripple mask, nullable
* @param ctx current context
* @return a substitute drawable, or null
*/
Drawable onFallback(ColorStateList color, Drawable content,
Drawable mask, Context ctx);
}
================================================
FILE: folivora/src/main/java/cn/cricin/folivora/ShapeAttrs.java
================================================
/*
* Copyright (C) 2019 Cricin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.cricin.folivora;
/**
* ShapeAttrs represents for a set of shape xml attribute indexes,
* so we can refactor shape creating method to reduce boilerplate code
*/
final class ShapeAttrs {
int[] mAttrStyleable;
int mShapeType;
int mShapeSolidSize;
int mShapeSolidWidth;
int mShapeSolidHeight;
int mShapeGradientType;
int mShapeGradientRadius;
int mShapeGradientCenterX;
int mShapeGradientCenterY;
int mShapeGradientStartColor;
int mShapeGradientCenterColor;
int mShapeGradientEndColor;
int mShapeGradientAngle;
int mShapeSolidColor;
int mShapeStrokeWidth;
int mShapeStrokeColor;
int mShapeStrokeDashGap;
int mShapeStrokeDashWidth;
int mShapeCornerRadius;
int mShapeCornerRadiusTopLeft;
int mShapeCornerRadiusTopRight;
int mShapeCornerRadiusBottomLeft;
int mShapeCornerRadiusBottomRight;
private ShapeAttrs(
int[] attrStyleable,
int shapeType,
int shapeSolidSize,
int shapeSolidWidth,
int shapeSolidHeight,
int shapeGradientType,
int shapeGradientRadius,
int shapeGradientCenterX,
int shapeGradientCenterY,
int shapeGradientStartColor,
int shapeGradientCenterColor,
int shapeGradientEndColor,
int shapeGradientAngle,
int shapeSolidColor,
int shapeStrokeWidth,
int shapeStrokeColor,
int shapeStrokeDashGap,
int shapeStrokeDashWidth,
int shapeCornerRadius,
int shapeCornerRadiusTopLeft,
int shapeCornerRadiusTopRight,
int shapeCornerRadiusBottomLeft,
int shapeCornerRadiusBottomRight
) {
this.mAttrStyleable = attrStyleable;
this.mShapeType = shapeType;
this.mShapeSolidSize = shapeSolidSize;
this.mShapeSolidWidth = shapeSolidWidth;
this.mShapeSolidHeight = shapeSolidHeight;
this.mShapeGradientType = shapeGradientType;
this.mShapeGradientRadius = shapeGradientRadius;
this.mShapeGradientCenterX = shapeGradientCenterX;
this.mShapeGradientCenterY = shapeGradientCenterY;
this.mShapeGradientStartColor = shapeGradientStartColor;
this.mShapeGradientCenterColor = shapeGradientCenterColor;
this.mShapeGradientEndColor = shapeGradientEndColor;
this.mShapeGradientAngle = shapeGradientAngle;
this.mShapeSolidColor = shapeSolidColor;
this.mShapeStrokeWidth = shapeStrokeWidth;
this.mShapeStrokeColor = shapeStrokeColor;
this.mShapeStrokeDashGap = shapeStrokeDashGap;
this.mShapeStrokeDashWidth = shapeStrokeDashWidth;
this.mShapeCornerRadius = shapeCornerRadius;
this.mShapeCornerRadiusTopLeft = shapeCornerRadiusTopLeft;
this.mShapeCornerRadiusTopRight = shapeCornerRadiusTopRight;
this.mShapeCornerRadiusBottomLeft = shapeCornerRadiusBottomLeft;
this.mShapeCornerRadiusBottomRight = shapeCornerRadiusBottomRight;
}
private static final ShapeAttrs[] SHAPE_ATTRS_ARRAY = {
new ShapeAttrs(
R.styleable.Folivora_Shape,
R.styleable.Folivora_Shape_shapeType,
R.styleable.Folivora_Shape_shapeSolidSize,
R.styleable.Folivora_Shape_shapeSolidWidth,
R.styleable.Folivora_Shape_shapeSolidHeight,
R.styleable.Folivora_Shape_shapeGradientType,
R.styleable.Folivora_Shape_shapeGradientRadius,
R.styleable.Folivora_Shape_shapeGradientCenterX,
R.styleable.Folivora_Shape_shapeGradientCenterY,
R.styleable.Folivora_Shape_shapeGradientStartColor,
R.styleable.Folivora_Shape_shapeGradientEndColor,
R.styleable.Folivora_Shape_shapeGradientCenterColor,
R.styleable.Folivora_Shape_shapeGradientAngle,
R.styleable.Folivora_Shape_shapeSolidColor,
R.styleable.Folivora_Shape_shapeStrokeWidth,
R.styleable.Folivora_Shape_shapeStrokeColor,
R.styleable.Folivora_Shape_shapeStokeDashGap,
R.styleable.Folivora_Shape_shapeStokeDashWidth,
R.styleable.Folivora_Shape_shapeCornerRadius,
R.styleable.Folivora_Shape_shapeCornerRadiusTopLeft,
R.styleable.Folivora_Shape_shapeCornerRadiusTopRight,
R.styleable.Folivora_Shape_shapeCornerRadiusBottomRight,
R.styleable.Folivora_Shape_shapeCornerRadiusBottomLeft
),
new ShapeAttrs(
R.styleable.Folivora_Shape1,
R.styleable.Folivora_Shape1_shape1Type,
R.styleable.Folivora_Shape1_shape1SolidSize,
R.styleable.Folivora_Shape1_shape1SolidWidth,
R.styleable.Folivora_Shape1_shape1SolidHeight,
R.styleable.Folivora_Shape1_shape1GradientType,
R.styleable.Folivora_Shape1_shape1GradientRadius,
R.styleable.Folivora_Shape1_shape1GradientCenterX,
R.styleable.Folivora_Shape1_shape1GradientCenterY,
R.styleable.Folivora_Shape1_shape1GradientStartColor,
R.styleable.Folivora_Shape1_shape1GradientEndColor,
R.styleable.Folivora_Shape1_shape1GradientCenterColor,
R.styleable.Folivora_Shape1_shape1GradientAngle,
R.styleable.Folivora_Shape1_shape1SolidColor,
R.styleable.Folivora_Shape1_shape1StrokeWidth,
R.styleable.Folivora_Shape1_shape1StrokeColor,
R.styleable.Folivora_Shape1_shape1StokeDashGap,
R.styleable.Folivora_Shape1_shape1StokeDashWidth,
R.styleable.Folivora_Shape1_shape1CornerRadius,
R.styleable.Folivora_Shape1_shape1CornerRadiusTopLeft,
R.styleable.Folivora_Shape1_shape1CornerRadiusTopRight,
R.styleable.Folivora_Shape1_shape1CornerRadiusBottomRight,
R.styleable.Folivora_Shape1_shape1CornerRadiusBottomLeft
),
new ShapeAttrs(
R.styleable.Folivora_Shape2,
R.styleable.Folivora_Shape2_shape2Type,
R.styleable.Folivora_Shape2_shape2SolidSize,
R.styleable.Folivora_Shape2_shape2SolidWidth,
R.styleable.Folivora_Shape2_shape2SolidHeight,
R.styleable.Folivora_Shape2_shape2GradientType,
R.styleable.Folivora_Shape2_shape2GradientRadius,
R.styleable.Folivora_Shape2_shape2GradientCenterX,
R.styleable.Folivora_Shape2_shape2GradientCenterY,
R.styleable.Folivora_Shape2_shape2GradientStartColor,
R.styleable.Folivora_Shape2_shape2GradientEndColor,
R.styleable.Folivora_Shape2_shape2GradientCenterColor,
R.styleable.Folivora_Shape2_shape2GradientAngle,
R.styleable.Folivora_Shape2_shape2SolidColor,
R.styleable.Folivora_Shape2_shape2StrokeWidth,
R.styleable.Folivora_Shape2_shape2StrokeColor,
R.styleable.Folivora_Shape2_shape2StokeDashGap,
R.styleable.Folivora_Shape2_shape2StokeDashWidth,
R.styleable.Folivora_Shape2_shape2CornerRadius,
R.styleable.Folivora_Shape2_shape2CornerRadiusTopLeft,
R.styleable.Folivora_Shape2_shape2CornerRadiusTopRight,
R.styleable.Folivora_Shape2_shape2CornerRadiusBottomRight,
R.styleable.Folivora_Shape2_shape2CornerRadiusBottomLeft
),
new ShapeAttrs(
R.styleable.Folivora_Shape3,
R.styleable.Folivora_Shape3_shape3Type,
R.styleable.Folivora_Shape3_shape3SolidSize,
R.styleable.Folivora_Shape3_shape3SolidWidth,
R.styleable.Folivora_Shape3_shape3SolidHeight,
R.styleable.Folivora_Shape3_shape3GradientType,
R.styleable.Folivora_Shape3_shape3GradientRadius,
R.styleable.Folivora_Shape3_shape3GradientCenterX,
R.styleable.Folivora_Shape3_shape3GradientCenterY,
R.styleable.Folivora_Shape3_shape3GradientStartColor,
R.styleable.Folivora_Shape3_shape3GradientEndColor,
R.styleable.Folivora_Shape3_shape3GradientCenterColor,
R.styleable.Folivora_Shape3_shape3GradientAngle,
R.styleable.Folivora_Shape3_shape3SolidColor,
R.styleable.Folivora_Shape3_shape3StrokeWidth,
R.styleable.Folivora_Shape3_shape3StrokeColor,
R.styleable.Folivora_Shape3_shape3StokeDashGap,
R.styleable.Folivora_Shape3_shape3StokeDashWidth,
R.styleable.Folivora_Shape3_shape3CornerRadius,
R.styleable.Folivora_Shape3_shape3CornerRadiusTopLeft,
R.styleable.Folivora_Shape3_shape3CornerRadiusTopRight,
R.styleable.Folivora_Shape3_shape3CornerRadiusBottomRight,
R.styleable.Folivora_Shape3_shape3CornerRadiusBottomLeft
),
new ShapeAttrs(
R.styleable.Folivora_Shape4,
R.styleable.Folivora_Shape4_shape4Type,
R.styleable.Folivora_Shape4_shape4SolidSize,
R.styleable.Folivora_Shape4_shape4SolidWidth,
R.styleable.Folivora_Shape4_shape4SolidHeight,
R.styleable.Folivora_Shape4_shape4GradientType,
R.styleable.Folivora_Shape4_shape4GradientRadius,
R.styleable.Folivora_Shape4_shape4GradientCenterX,
R.styleable.Folivora_Shape4_shape4GradientCenterY,
R.styleable.Folivora_Shape4_shape4GradientStartColor,
R.styleable.Folivora_Shape4_shape4GradientEndColor,
R.styleable.Folivora_Shape4_shape4GradientCenterColor,
R.styleable.Folivora_Shape4_shape4GradientAngle,
R.styleable.Folivora_Shape4_shape4SolidColor,
R.styleable.Folivora_Shape4_shape4StrokeWidth,
R.styleable.Folivora_Shape4_shape4StrokeColor,
R.styleable.Folivora_Shape4_shape4StokeDashGap,
R.styleable.Folivora_Shape4_shape4StokeDashWidth,
R.styleable.Folivora_Shape4_shape4CornerRadius,
R.styleable.Folivora_Shape4_shape4CornerRadiusTopLeft,
R.styleable.Folivora_Shape4_shape4CornerRadiusTopRight,
R.styleable.Folivora_Shape4_shape4CornerRadiusBottomRight,
R.styleable.Folivora_Shape4_shape4CornerRadiusBottomLeft
)
};
static ShapeAttrs forIndex(int index) {
if (index < 0 || index > 4) {
return null;
} else {
return SHAPE_ATTRS_ARRAY[index];
}
}
}
================================================
FILE: folivora/src/main/res/values/attrs.xml
================================================
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Sat Mar 21 17:57:59 CST 2020
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip
================================================
FILE: gradle.properties
================================================
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
android.useAndroidX=true
================================================
FILE: gradlew
================================================
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
================================================
FILE: gradlew.bat
================================================
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
================================================
FILE: lint/build.gradle
================================================
apply plugin: 'java'
def ideInstallationDir = new File('d:/android/studio')
def androidPluginLibPath = 'plugins/android/lib'
def lintVersion = '26.2.0-alpha06'
configurations.all {
transitive = false
}
dependencies {
compileOnly "com.android.tools.lint:lint-api:$lintVersion"
compileOnly "com.android.tools.lint:lint-checks:$lintVersion"
compileOnly "com.android.tools.lint:lint:$lintVersion"
compileOnly "com.android.tools.external.org-jetbrains:uast:$lintVersion"
compileOnly "com.android.tools.external.com-intellij:intellij-core:$lintVersion"
compileOnly 'com.android.tools:common:26.6.1'
compileOnly 'com.android.tools.layoutlib:layoutlib-api:26.6.1'
if (ideInstallationDir.exists() && ideInstallationDir.isDirectory()) {
["${androidPluginLibPath}/android.jar",
'lib/openapi.jar',
'lib/platform-api.jar',
'lib/idea.jar'
].each { lib ->
def file = new File(ideInstallationDir, lib)
if(!file.exists()) throw new Exception("file $file does not exist")
compileOnly files(file)
}
def legacyLayoutLib = new File("${androidPluginLibPath}/layoutlib.jar")
def layoutLib = new File(ideInstallationDir, "plugins/android-layoutlib/lib/layoutlib.jar")
if (legacyLayoutLib.exists()) {
compileOnly files(legacyLayoutLib)
} else if(layoutLib.exists()) {
compileOnly files(layoutLib)
} else {
throw new Exception("layoutlib does not exist")
}
} else {
throw new GradleException('Invalid ide installation dir')
}
}
jar {
manifest {
attributes("Lint-Registry-v2": "cn.cricin.folivora.lint.FolivoraIssueRegistry")
attributes("Lint-Registry": "cn.cricin.folivora.lint.FolivoraIssueRegistry")
}
archiveName('folivora-lint.jar')
}
task installLint(type: Copy) {
setGroup('install')
def jarTask = tasks.findByName('jar')
dependsOn(jarTask)
from(jarTask.outputs.files)
into(new File(new File(System.getProperty("user.home")), '.android/lint/'))
}
task uninstallLint() {
setGroup('install')
doFirst {
File lintLibDir = new File(new File(System.getProperty("user.home")), '.android/lint')
def folivoraLintJar = new File(lintLibDir, 'folivora-lint.jar')
if (folivoraLintJar.exists()) {
folivoraLintJar.delete()
}
}
}
================================================
FILE: lint/src/main/java/cn/cricin/folivora/dom/AndroidFacetCompat.java
================================================
/*
* Copyright (C) 2019 Cricin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.cricin.folivora.dom;
import com.android.tools.idea.model.AndroidModel;
import com.intellij.openapi.util.Pair;
import org.jetbrains.android.dom.manifest.Manifest;
import org.jetbrains.android.facet.AndroidFacet;
import org.jetbrains.android.resourceManagers.LocalResourceManager;
import org.jetbrains.android.resourceManagers.ModuleResourceManagers;
import org.jetbrains.android.resourceManagers.ResourceManager;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
/**
* Since the API of AndroidFacet class changed so frequently
* in different version of Android Studio, a compat utility
* is needed for those API changes.
*/
final class AndroidFacetCompat {
private static boolean sModuleResourceManagerExists = true;
static ResourceManager getAppResourceManager(AndroidFacet facet) {
ResourceManager manager = null;
if (sModuleResourceManagerExists) {
try {
manager = ModuleResourceManagers.getInstance(facet).getResourceManager(null);
} catch (Throwable ignore) {
sModuleResourceManagerExists = false;
}
}
if (!sModuleResourceManagerExists) {
manager = LocalResourceManager.getInstance(facet.getModule());
}
return manager;
}
/**
* Added for android studio 3.0
*/
static boolean isAppProject(AndroidFacet facet) {
Boolean value = invoke(AndroidFacet.class, "isAppProject", facet, null, null, new Callable() {
@Override
public Boolean call() throws Exception {
return facet.getConfiguration().isAppProject();
}
});
return value != null && value;
}
/**
* Added for android studio 4.0 canary release
*/
static boolean requiresAndroidModel(AndroidFacet facet) {
Boolean value = invoke(AndroidModel.class, "isRequired", null, new Class[]{AndroidFacet.class}, new Object[]{facet}, new Callable() {
@Override
public Boolean call() throws Exception {
return facet.requiresAndroidModel();
}
});
return value != null && value;
}
/**
* Added for android studio 4.0 canary release
*/
static Manifest getManifest(AndroidFacet facet) {
return invoke(AndroidFacet.class, "getManifest", facet, null, null, new Callable() {
@Override
public Manifest call() throws Exception {
return Manifest.getMainManifest(facet);
}
});
}
private static Map, String>, Method> sInvokableMethods = new HashMap<>();
@SuppressWarnings("unchecked")
private static R invoke(Class> clazz, String methodName, Object receiver, Class>[] argClasses, Object[] args, Callable c) {
final Pair, String> pair = Pair.create(clazz, methodName);
Method method = sInvokableMethods.get(pair);
if (method != null) {
try {
return (R) method.invoke(receiver, args);
} catch (Throwable ignore) {
}
}
try {
return c.call();
} catch (Throwable ignore) {
}
try {
method = clazz.getDeclaredMethod(methodName, argClasses);
Object result = method.invoke(receiver, args);
sInvokableMethods.put(pair, method);
return (R) result;
} catch (Throwable ignore) {
}
return null;
}
private AndroidFacetCompat() {
}
}
================================================
FILE: lint/src/main/java/cn/cricin/folivora/dom/DrawableIdConverter.java
================================================
/*
* Copyright (C) 2019 Cricin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.cricin.folivora.dom;
import com.android.SdkConstants;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiRecursiveElementVisitor;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.xml.ConvertContext;
import com.intellij.util.xml.ResolvingConverter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* This converter keeps track app:drawableId values used
* in project, and gives cached candidates when use drawableId
*/
public class DrawableIdConverter extends ResolvingConverter {
@NotNull
@Override
public Collection extends String> getVariants(ConvertContext convertContext) {
if (convertContext == null) return Collections.emptyList();
XmlFile file = convertContext.getFile();
final Set drawableIds = new HashSet<>();
file.accept(new PsiRecursiveElementVisitor() {
@Override
public void visitElement(PsiElement element) {
super.visitElement(element);
if (element instanceof XmlTag) {
String drawableId = ((XmlTag) element).getAttributeValue("drawableId", SdkConstants.AUTO_URI);
if(drawableId != null && !drawableId.isEmpty()) {
drawableIds.add(drawableId);
}
}
}
});
return new ArrayList<>(drawableIds);
}
@Nullable
@Override
public String fromString(@Nullable String s, ConvertContext convertContext) {
return s;
}
@Nullable
@Override
public String toString(@Nullable String s, ConvertContext convertContext) {
return s;
}
}
================================================
FILE: lint/src/main/java/cn/cricin/folivora/dom/FolivoraAttrProcessing.java
================================================
/*
* Copyright (C) 2019 Cricin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.cricin.folivora.dom;
import com.android.SdkConstants;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.xml.Converter;
import com.intellij.util.xml.DomElement;
import com.intellij.util.xml.XmlName;
import com.intellij.util.xml.reflect.DomExtension;
import org.jetbrains.android.dom.AndroidDomElement;
import org.jetbrains.android.dom.AndroidDomUtil;
import org.jetbrains.android.dom.AttributeProcessingUtil;
import org.jetbrains.android.dom.attrs.AttributeDefinition;
import org.jetbrains.android.dom.attrs.AttributeDefinitions;
import org.jetbrains.android.dom.attrs.StyleableDefinition;
import org.jetbrains.android.dom.attrs.ToolsAttributeUtil;
import org.jetbrains.android.dom.converters.CompositeConverter;
import org.jetbrains.android.dom.converters.PackageClassConverter;
import org.jetbrains.android.dom.converters.ResourceReferenceConverter;
import org.jetbrains.android.dom.layout.DataBindingElement;
import org.jetbrains.android.dom.layout.LayoutElement;
import org.jetbrains.android.dom.manifest.Manifest;
import org.jetbrains.android.facet.AndroidFacet;
import org.jetbrains.android.resourceManagers.ResourceManager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
/**
* Process folivora attr's to the current dom element
*/
final class FolivoraAttrProcessing {
/**
* If this attr name exists in xml tag, it's value is treated as
* declare styleables, folivora will also register these attributes
* to current xml tag.
*/
private static final String EXTRA_STYLEABLE_ATTR_NAME = "extraStyleables";
/**
* This converter is used to find custom drawable classes in current project
*/
private static final PackageClassConverter DRAWABLE_CLASS_CONVERTER =
new PackageClassConverter("android.graphics.drawable.Drawable");
private static final DrawableIdConverter DRAWABLE_ID_CONVERTER = new DrawableIdConverter();
private static final HashMap TYPE_TO_STYLEABLE = new HashMap<>();
private static final HashMap SHAPE_TO_STYLEABLE = new HashMap<>();
static {
TYPE_TO_STYLEABLE.put("shape", "Folivora_Shape");
TYPE_TO_STYLEABLE.put("selector", "Folivora_Selector");
TYPE_TO_STYLEABLE.put("layer_list", "Folivora_Layer");
TYPE_TO_STYLEABLE.put("ripple", "Folivora_Ripple");
TYPE_TO_STYLEABLE.put("level_list", "Folivora_Level");
TYPE_TO_STYLEABLE.put("clip", "Folivora_Clip");
TYPE_TO_STYLEABLE.put("inset", "Folivora_Inset");
TYPE_TO_STYLEABLE.put("scale", "Folivora_Scale");
TYPE_TO_STYLEABLE.put("animation", "Folivora_Animation");
SHAPE_TO_STYLEABLE.put("shape", "Folivora_Shape");
SHAPE_TO_STYLEABLE.put("shape1", "Folivora_Shape1");
SHAPE_TO_STYLEABLE.put("shape2", "Folivora_Shape2");
SHAPE_TO_STYLEABLE.put("shape3", "Folivora_Shape3");
SHAPE_TO_STYLEABLE.put("shape4", "Folivora_Shape4");
}
static void registerFolivoraAttributes(AndroidFacet facet,
AndroidDomElement element,
AttributeProcessingUtil.AttributeProcessor callback) {
if (!(element instanceof LayoutElement)) return;
if (element instanceof DataBindingElement) return;
XmlTag tag = element.getXmlTag();
if (tag == null) return;
if (isInvalidTagName(tag.getName())) return;
List styleableNames = getStyleablesToRegister(tag.getAttributes());
for (String styleableName : styleableNames) {
if (styleableName != null && styleableName.length() > 0) {
registerAttributes(facet, element, styleableName, callback);
}
}
}
private static List getStyleablesToRegister(XmlAttribute[] attrs) {
List styleableNames = new ArrayList<>(6);
styleableNames.add("Folivora");
String drawableType = null;
String drawableName = null;
for (XmlAttribute attr : attrs) {
String attrName = attr.getLocalName();
String attrValue = attr.getValue();
if ("drawableType".equals(attrName)) {
drawableType = attrValue;
} else if ("drawableName".equals(attrName)) {
drawableName = attrValue;
} else if (EXTRA_STYLEABLE_ATTR_NAME.equals(attrName) && attrValue != null) {
if (attrValue.indexOf(',') != -1) {
styleableNames.addAll(Arrays.asList(attrValue.split(",")));
} else {
styleableNames.add(attrValue);
}
}
}
if (drawableType == null && drawableName == null) return styleableNames;
if (drawableType != null) styleableNames.add(TYPE_TO_STYLEABLE.get(drawableType));
if (drawableName != null) styleableNames.add(getSimpleClassName(drawableName));
// process nested shapes
String styleable;
for (XmlAttribute attr : attrs) {
String attrName = attr.getLocalName();
String attrValue = attr.getValue();
if (attrName.startsWith("shape1")
|| attrName.startsWith("shape2")
|| attrName.startsWith("shape3")
|| attrName.startsWith("shape4")) continue;
styleable = SHAPE_TO_STYLEABLE.get(attrValue);
if (styleable == null) continue;
if (drawableType != null && attrName.startsWith(drawableType)) {
styleableNames.add(styleable);
} else if (drawableName != null) {
// if is custom drawable, we don't know whether this drawable
// need nested shapes, so register nested shape anyway
styleableNames.add(styleable);
}
}
return styleableNames;
}
private static String getSimpleClassName(String className) {
if (className == null) return null;
int dotIndex = className.lastIndexOf('.');
if (dotIndex == -1 || dotIndex + 1 >= className.length()) return null;
return className.substring(dotIndex + 1);
}
private static boolean isInvalidTagName(String tagName) {
return "layout".equals(tagName)
|| "fragment".equals(tagName)
|| "include".equals(tagName)
|| "requestFocus".equals(tagName)
|| "merge".equals(tagName);
}
private static void registerAttributes(/*NotNull*/ AndroidFacet facet,
/*NotNull*/ DomElement element,
/*NotNull*/ String styleableName,
/*NotNull*/ AttributeProcessingUtil.AttributeProcessor callback) {
ResourceManager manager = AndroidFacetCompat.getAppResourceManager(facet);
if (manager == null) {
return;
}
AttributeDefinitions attrDefs = manager.getAttributeDefinitions();
if (attrDefs == null) {
return;
}
String namespace = getNamespaceUriByResourcePackage(facet, null);
StyleableDefinition styleable = attrDefs.getStyleableByName(styleableName);
if (styleable != null) {
registerStyleableAttributes(element, styleable, namespace, callback);
}
// It's a good idea to add a warning when styleable not found, to make sure that code doesn't
// try to use attributes that don't exist. However, current AndroidDomExtender code relies on
// a lot of "heuristics" that fail quite a lot (like adding a bunch of suffixes to short
// class names)
// TODO: add a warning when rest of the code of AndroidDomExtender is cleaned up
}
/*Nullable*/
private static String getNamespaceUriByResourcePackage(/*NotNull*/ AndroidFacet facet,
/*Nullable*/ String resPackage) {
if (resPackage == null) {
if (!AndroidFacetCompat.isAppProject(facet)|| AndroidFacetCompat.requiresAndroidModel(facet)) {
return SdkConstants.AUTO_URI;
}
Manifest manifest = AndroidFacetCompat.getManifest(facet);
if (manifest != null) {
String aPackage = manifest.getPackage().getValue();
if (aPackage != null && !aPackage.isEmpty()) {
return SdkConstants.URI_PREFIX + aPackage;
}
}
} else if (resPackage.equals(SdkConstants.ANDROID_NS_NAME)) {
return SdkConstants.ANDROID_URI;
}
return null;
}
private static void registerStyleableAttributes(
/*NotNull*/ DomElement element,
/*NotNull*/ StyleableDefinition styleable,
/*Nullable*/ String namespaceUri,
/*NotNull*/ AttributeProcessingUtil.AttributeProcessor callback) {
for (AttributeDefinition attrDef : styleable.getAttributes()) {
registerAttribute(attrDef, styleable.getName(), namespaceUri, element, callback);
}
}
private static void registerAttribute(
AttributeDefinition attrDef,
String parentStyleableName,
String namespaceKey,
DomElement element,
AttributeProcessingUtil.AttributeProcessor callback) {
String name = attrDef.getName();
if (!SdkConstants.ANDROID_URI.equals(namespaceKey) && name.startsWith(SdkConstants.ANDROID_NS_NAME_PREFIX)) {
name = name.substring(SdkConstants.ANDROID_NS_NAME_PREFIX.length());
namespaceKey = SdkConstants.ANDROID_URI;
}
XmlName xmlName = new XmlName(name, namespaceKey);
DomExtension extension = callback.processAttribute(xmlName, attrDef, parentStyleableName);
if (extension != null) {
Converter converter = AndroidDomUtil.getSpecificConverter(xmlName, element);
if ("drawableName".equals(name)) {
converter = DRAWABLE_CLASS_CONVERTER;
}
if ("drawableId".equals(name)) {
converter = DRAWABLE_ID_CONVERTER;
}
if (converter == null) {
if (SdkConstants.TOOLS_URI.equals(namespaceKey)) {
converter = ToolsAttributeUtil.getConverter(attrDef);
} else {
converter = AndroidDomUtil.getConverter(attrDef);
}
}
if (converter != null) {
extension.setConverter(converter, mustBeSoft(converter, attrDef.getFormats()));
}
}
}
private static boolean mustBeSoft(Converter converter, Collection formats) {
if (!(converter instanceof CompositeConverter)
&& !(converter instanceof ResourceReferenceConverter)) {
return formats.size() > 1;
} else {
return false;
}
}
private FolivoraAttrProcessing() {}
}
================================================
FILE: lint/src/main/java/cn/cricin/folivora/dom/FolivoraDomExtender.java
================================================
/*
* Copyright (C) 2019 Cricin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.cricin.folivora.dom;
import com.intellij.openapi.extensions.ExtensionPoint;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.util.xml.GenericAttributeValue;
import com.intellij.util.xml.reflect.DomExtender;
import com.intellij.util.xml.reflect.DomExtenderEP;
import com.intellij.util.xml.reflect.DomExtensionsRegistrar;
import org.jetbrains.android.dom.AndroidDomElement;
import org.jetbrains.android.dom.AttributeProcessingUtil;
import org.jetbrains.android.dom.resources.ResourceValue;
import org.jetbrains.android.facet.AndroidFacet;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Set;
import javax.annotation.Nonnull;
@SuppressWarnings("unchecked")
public final class FolivoraDomExtender extends DomExtender {
private static HashMap