> 文档中心 > BackgroundLibrary库使用与技巧

BackgroundLibrary库使用与技巧

库地址:https://github.com/JavaNoober/BackgroundLibrary

为了解决在项目中大量的样式文件,例如shpre,selector等文件,引入BackgroundLibrary库。下面介绍一下BackgroundLibrary的使用。

  • 优点:减少了大量xml文件的创建
  • 缺点:不可以预览,需要写很多app属性(app的属性值可以根据蓝湖的UI上的代码来代入),不过写多了应该就熟悉了,哈哈。
  • 性能:暂时没有发现,库的原理只是把原本该交给系统从xml解析属性创建Drawable的功能,换成自己实现而已。

1.依赖导入

依赖方式:

allprojects {    repositories { ... maven { url 'https://jitpack.io' }    }}implementation "com.android.support:appcompat-v7:$supportVersion"implementation 'com.github.JavaNoober.BackgroundLibrary:library:1.7.3'

如果项目使用了androidx:

allprojects {    repositories { ... maven { url 'https://jitpack.io' }    }}implementation "androidx.appcompat:appcompat:$supportVersion" implementation 'com.github.JavaNoober.BackgroundLibrary:libraryx:1.7.3'

2.源码导入

根据自己项目的是否是androidx选择libraryx或者library

 3.使用

下面举几个常用的样式。
1、边框+背景+圆角

等同于

            

2、渐变

        

等同于

 

3、点击效果

4.开发技巧

关于自定义属性爆红的问题,这里有两个解决方案:
1.一种是在使用到这个属性的地方,同步添加 tools:ignore="MissingPrefix"
2.另一种方式是使用 AppCompat前缀控件替换掉普通的控件,比如说 TextView 替换为 AppCompatTextViewEditText 替换为 AppCompatEditText 等,,其他控件类似,或者是继承于AppCompat控件的。

关于如何进行代码提示:
配置Live Templates步骤:
以Android studio3.2为例:
mac:进入目录MacintoshHD\user\xxx\Library\Preferences\AndroidStudio3.2\templates
mac as4.0 之后目录进行了修改:
/Users/xxx/Library/Application Support/Google/AndroidStudio4.1/templates
windows:进入目录C:\Users\XXX.AndroidStudio3.2\config\templates
windows as4.0之后:
C:\Users\xxx\AppData\Roaming\Google\AndroidStudio4.0\templates
如果templates不存在,手动创建文件夹即可; 在templates下面加入文件BackgroundLibrary.xml 重启as即可。

如何预览:
1、如果需要对View进行预览,直接把原来的View换成框架内对应的BLView即可,即可展示预览效果,如果不需要预览可以直接忽略这些用于预览的自定义View;
2、如果没有效果,make project一下即可;
3、如果BLView中没有对应的需要预览的View,可以很简单的自己实现一下,以BLTextView为例:

public class BLTextView extends AppCompatTextView {    public BLTextView(Context context) { super(context);    }    public BLTextView(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs);    }    public BLTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs);    }    private void init(Context context, AttributeSet attrs){ BackgroundFactory.setViewBackground(context, attrs, this);    }}

继承所需要预览的View,然后在构造函数中添加BackgroundFactory.setViewBackground(context, attrs, this)方法即可。