Я пишу модульные тесты (используя robolectric 3.1
) для проекта компании. В недавней фиксации версия android gradle plugin
была обновлена с 2.1.0
до 2.2.3
. Это изменение вызвало ошибки при сбое всякий раз, когда тест вызывает код, который загружает пользовательские шрифты.пользовательские шрифты не могут загружаться во время модульных тестов после обновления плагина android gradle
Изменение версии плагина назад до 2.1.0
устраняет проблему, но мне сказали, что изменение версии требуется и должно остаться. В любом случае, наша среда сборки CI не имеет проблем с тестированием, поэтому кажется, что проблема возникает только для моей локальной сборки.
Я обновил JRE и SDK, как 1.8 (и установил JAVA_HOME в обновленный каталог JDK), так и Android Studio, но безуспешно. Каталог активов правильно помещается в директорию «main», а не «res» (шрифты указаны в приложении/src/main/assets/fonts /). Очистка проекта и повторная инициализация IDE с помощью кэширования также не помогли.
Проблема сохраняется после выключения Instant Сбегайте, так что это не один описанный здесь https://code.google.com/p/android/issues/detail?id=213454
build.gradle:
dependencies {
(...)
classpath 'com.android.tools.build:gradle:2.2.3'
}
android {
compileSdkVersion 23
buildToolsVersion '23.0.2'
defaultConfig {
applicationId "com.example.app"
minSdkVersion 16
targetSdkVersion 22
multiDexEnabled true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
(...)
}
Пример кода с использованием пользовательских шрифтов (макет):
<com.example.CustomFontTextView
(...)
android:textAppearance="?android:attr/textAppearanceSmall"
custom:customFont="@string/custom_font_path"/>
Пользовательские f ОНТ вид текста:
public class CustomFontTextView extends TextView {
public CustomFontTextView(final Context context){
super(context);
}
public CustomFontTextView (final Context context, final AttributeSet attrs){
super(context, attrs);
if(!isInEditMode()){
initTextView(context, attrs);
}
}
public CustomFontTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
if(!isInEditMode()){
initTextView(context, attrs);
}
}
private void initTextView(final Context context, final AttributeSet attrs){
TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.CustomFontView);
String customFont = attributes.getString(R.styleable.CustomFontView_customFont);
setText(getText());
if(customFont!=null){
Typeface tf = getTypeface(context, customFont);
setTypeface(tf);
}
attributes.recycle();
}
private Typeface getTypeface(final Context context, final String customFontPath) {
return Typeface.createFromAsset(context.getAssets(), customFontPath);
}
public void setTypeFace(Context con, String font){
if(font != null && con != null){
Typeface tf = getTypeface(con, font);
setTypeface(tf);
}
}
}
attrs.xml:
<declare-styleable name="CustomFontView">
<attr name="customFont" format="string" />
</declare-styleable>
пути шрифта хранятся в строках:
<string name="custom_font_path">fonts/CustomFont.ttf</string>
Exception (происходит при наполнении макета):
android.view.InflateException: XML file build\intermediates\res\merged\mock\debug\layout\layout.xml line #-1 (sorry, not yet implemented): Error inflating class <unknown>
(...)
Caused by: java.lang.RuntimeException: Font not found at [build\intermediates\bundles\mock\debug\assets\fonts\CustomFont.ttf]
Что вызывает нагрузку на шрифт терпеть неудачу? Является ли Robolectric виновным?
шрифт не найден в [построить \ промежуточные \ расслоения \ издеваться \ Debug \ активы \ Fonts \ CustomFont.ttf] – petey