Aapt error is incompatible with attribute src attr reference color

I am new to Android dev and am working on my first app. I have been running into trouble trying to get an image view set up with my own image (stock photos on studio are working fine), and am gett...

I am new to Android dev and am working on my first app. I have been running into trouble trying to get an image view set up with my own image (stock photos on studio are working fine), and am getting the following error:

AAPT: error: ‘/home/joshua/AndroidStudioProjects/WSC/app/src/main/res/mipmap-xxxhdpi/wsc_foreground.png’ is incompatible with attribute src (attr) reference|color.

I have researched around to even try to understand what this error is saying, and I think it is having trouble linking some file/resource?

I uploaded a .jpg using the add image asset option in android studio. I added a color background to the image, which was a hex number I selected.

I am not getting any errors or warnings until I build, at which point the build fails.

**Can someone please explain:

  1. What this error means.
  2. How to troubleshoot this.
  3. Where my mistake lies.**

I have attached the (hopefully sufficiently) relevant XML code.

Here is the image view inside of my fragment_first.xml, which is inside layout:

<ImageView
        android:id="@+id/wsc_image"
        android:layout_width="930dp"
        android:layout_height="585dp"
        android:layout_marginTop="44dp"
        android:contentDescription="@string/wsc_image_description"
        android:src="/home/joshua/AndroidStudioProjects/WSC/app/src/main/res/mipmap-xxxhdpi/wsc_foreground.png"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/textview_first"
        app:layout_constraintStart_toStartOf="@+id/textview_first"
        app:layout_constraintTop_toBottomOf="@+id/textview_first"
        app:layout_constraintVertical_bias="0.0" />

I don’t have an XML for the wsc_foreground.png, but do have a wsc.xml. I tried adding the full path in the wsc.xml for wsc_foreground.png, but this did not change anything.

<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
    <background android:drawable="@color/wsc_background"/>
    <foreground android:drawable="/home/joshua/AndroidStudioProjects/WSC/app/src/main/res/mipmap-xxxhdpi/wsc_foreground.png"/>
</adaptive-icon>

My apologies if this is a dumb question and/or not clear. Please let me know in the comments if I need to clarify any of this.

Thanks!

Устранение неполадок: AAPT: ошибка: несовместимо с атрибутом src (attr) reference | color

Я новичок в разработке Android и работаю над своим первым приложением. У меня возникли проблемы с попыткой настроить просмотр изображения с помощью моего собственного изображения (стоковые фотографии в студии работают нормально), и я получаю следующую ошибку:

AAPT: ошибка: ‘/home/joshua/AndroidStudioProjects/WSC/app/src/main/res/mipmap-xxxhdpi/wsc_foreground.png’ несовместимо с атрибутом src (attr) reference | color.

Я исследовал все вокруг, чтобы даже попытаться понять, о чем говорит эта ошибка, и я думаю, что у него проблемы с связыванием какого-либо файла / ресурса?

Я загрузил .jpg с помощью опции добавления изображения в студию Android. Я добавил к изображению цветной фон — выбранное мной шестнадцатеричное число.

Я не получаю никаких ошибок или предупреждений, пока не начну сборку, после чего сборка завершится ошибкой.

** Может кто-нибудь объяснить:

  1. Что означает эта ошибка.
  2. Как это исправить.
  3. В чем моя ошибка. **

Я приложил (надеюсь, достаточно) соответствующий XML-код.

Вот изображение внутри моего файла fragment_first.xml, который находится внутри макета:

У меня нет XML для wsc_foreground.png, но есть wsc.xml. Я попытался добавить полный путь к wsc_foreground.png в wsc.xml, но это ничего не изменило.

Приношу свои извинения, если это глупый вопрос и / или непонятный. Пожалуйста, дайте мне знать в комментариях, если мне нужно что-то прояснить.

Источник

I am new to Android dev and am working on my first app. I have been running into trouble trying to get an image view set up with my own image (stock photos on studio are working fine), and am getting the following error:

AAPT: error: ‘/home/joshua/AndroidStudioProjects/WSC/app/src/main/res/mipmap-xxxhdpi/wsc_foreground.png’ is incompatible with attribute src (attr) reference|color.

I have researched around to even try to understand what this error is saying, and I think it is having trouble linking some file/resource?

I uploaded a .jpg using the add image asset option in android studio. I added a color background to the image, which was a hex number I selected.

I am not getting any errors or warnings until I build, at which point the build fails.

**Can someone please explain:

  1. What this error means.
  2. How to troubleshoot this.
  3. Where my mistake lies.**

I have attached the (hopefully sufficiently) relevant XML code.

Here is the image view inside of my fragment_first.xml, which is inside layout:

<ImageView
        android:id="@+id/wsc_image"
        android:layout_width="930dp"
        android:layout_height="585dp"
        android:layout_marginTop="44dp"
        android:contentDescription="@string/wsc_image_description"
        android:src="/home/joshua/AndroidStudioProjects/WSC/app/src/main/res/mipmap-xxxhdpi/wsc_foreground.png"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/textview_first"
        app:layout_constraintStart_toStartOf="@+id/textview_first"
        app:layout_constraintTop_toBottomOf="@+id/textview_first"
        app:layout_constraintVertical_bias="0.0" />

I don’t have an XML for the wsc_foreground.png, but do have a wsc.xml. I tried adding the full path in the wsc.xml for wsc_foreground.png, but this did not change anything.

<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
    <background android:drawable="@color/wsc_background"/>
    <foreground android:drawable="/home/joshua/AndroidStudioProjects/WSC/app/src/main/res/mipmap-xxxhdpi/wsc_foreground.png"/>
</adaptive-icon>

My apologies if this is a dumb question and/or not clear. Please let me know in the comments if I need to clarify any of this.

Thanks!

Я добавил BottomNavigationView в моем приложении, как.

MAIN.XML

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:layout_width="match_parent"
    android:layout_height="56dp"
    app:itemBackground="@drawable/nav_bgcolor"
    app:itemIconSize="50dp"
    app:itemIconTint="@color/nav_item_colors"
    app:itemTextColor="@color/nav_item_colors"
    app:labelVisibilityMode="unlabeled"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:menu="@menu/nav_items">
</com.google.android.material.bottomnavigation.BottomNavigationView>

< Сильный > меню / nav_items.xml

<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/nav_home"
        android:icon="@drawable/home_white"
        android:title="@string/nav_home" />
    <item
        android:id="@+id/nav_market"
        android:icon="@drawable/market_white"
        android:title="@string/nav_market" />
    <item
        android:id="@+id/nav_news"
        android:icon="@drawable/news_white"
        android:title="@string/nav_news" />
    <item
        android:id="@+id/nav_account"
        android:icon="@drawable/account_white"
        android:title="@string/nav_account" />
</menu>

< Сильный > вытяжке / nav_bgcolor.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="#FF9800" android:state_checked="true" />
    <item android:drawable="#FFFFFF" android:state_checked="false" />
</selector>

< Сильный > цвет / nav_item_colors.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="#FFFFFF" android:state_checked="true"/>
    <item android:color="#727272"/>
</selector>

Это превью в андроид студии

https://drive.google.com/file/d/1yICxFcTbSxYpILDtxg75Z4x-2Y1UaPM_/view?usp=sharing

Это на самом деле отображает дизайн, который я хочу, чтобы это произошло.

Нет ошибки или чего-то еще, но когда я запускаю приложение, в drawable / nav_bgcolor.xml возникают ошибки

C:Users[PCNAME]AndroidStudioProjects[APPNAME]appsrcmainresdrawablenav_bgcolor.xml:3: AAPT: error: '#FF9800' is incompatible with attribute drawable (attr) reference.
C:Users[PCNAME]AndroidStudioProjects[APPNAME]appsrcmainresdrawablenav_bgcolor.xml:4: AAPT: error: '#ffffff' is incompatible with attribute drawable (attr) reference.

Ошибка произошла после того, как я добавил app: itemBackground = «@ drawable / nav_bgcolor» в main.xml

Я искал в интернете, но мне не повезло в поиске решения.

2 ответа

Лучший ответ

В вашем селекторе вы используете

<selector>
    <item android:drawable="#FF9800" android:state_checked="true" />

Вы не можете использовать цвет (#FF9800), где вы должны определить android:drawable.

Использовать

<menu>
    <item
        android:id="@+id/nav_home"
        android:icon="@drawable/icon_add"
        android:title="@string/nav_home" />
    ...
</menu>

Где icon_add — простая отрисовка.
И в вашем BottomNavigationView:

<com.google.android.material.bottomnavigation.BottomNavigationView
     app:itemIconTint="@color/nav_item_colors"
     ../>


0

Gabriele Mariotti
23 Окт 2019 в 22:47

заменить android: рисовать на android: цвет в drawable / nav_bgcolor.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="#FF9800" android:state_checked="true" />
    <item android:color="#FFFFFF" android:state_checked="false" />
</selector>


0

Hardik Bhalala
23 Окт 2019 в 13:23

У меня возникает эта проблема, когда я пытаюсь изменить свой android:background в XML-файле моей активности.

Information:Gradle tasks [:app:assembleDebug]
C:UsersValentinAndroidStudioProjectsCedarRestaurants4CedarRestaurants3appsrcmainreslayoutactivity_dynamic_view_ordering.xml
Error:error: 'drawable/delete' is incompatible with attribute android:background (attr) reference|color.
Error:'drawable/delete' is incompatible with attribute android:background (attr) reference|color.
Error:failed linking file resources.
Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:Execution failed for task ':app:processDebugResources'.
> Failed to execute aapt
Information:BUILD FAILED in 4s
Information:7 errors
Information:0 warnings
Information:See complete output in console

XML-файл моей активности:

<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
xmlns:android = "http://schemas.android.com/apk/res/android">

<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
    android:id = "@+id/parent_linear_layout"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    android:layout_margin = "5dp"
    android:orientation = "vertical" >
    <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
        android:layout_width = "match_parent"
        android:layout_height = "50dp"
        android:orientation = "horizontal" >
        <EditText
            android:id = "@+id/number_edit_text"
            android:layout_width = "0dp"
            android:layout_height = "match_parent"
            android:layout_weight = "5" />

        <Button
            android:id = "@+id/delete_button"
            android:layout_width = "0dp"
            android:layout_height = "wrap_content"
            android:layout_weight = "1"
            android:background = "drawable/delete.png"
            android:onClick = "onDelete" />
    </LinearLayout>
    <Button
        android:id = "@+id/add_field_button"
        android:layout_width = "100dp"
        android:layout_height = "wrap_content"
        android:layout_marginBottom = "5dp"
        android:layout_marginLeft = "5dp"
        android:layout_marginRight = "5dp"
        android:background = "#555"
        android:layout_gravity = "center"
        android:onClick = "onAddField"
        android:textColor = "#FFF"
        android:text = "New"
        android:paddingLeft = "5dp"/>
</LinearLayout>

<Button
    android:id = "@+id/placeOrderButton"
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"
    android:layout_alignBottom = "@+id/parent_linear_layout"
    android:layout_centerHorizontal = "true"
    android:layout_marginBottom = "250sp"
    android:text = "@string/place_order"
    android:textSize = "32sp" />


</RelativeLayout>

Я скопировал файл макета активности и активность из учебного проекта и пытаюсь изменить ресурсы изображения на что-то более современное.

Я уже убедился, что мой delete.png внутри /src/main/res/drawable, и уже пытался избавиться от .png в конце, но безуспешно. Любая помощь приветствуется.

Issue

I was doing the layout and when starting the emulator I got this error
I tried to clean the code and rebuild it also I already reinstalled the android studio.
Also I tried «Invalidate Caches» but the problem still exists

I read on the medium that you need to remove ‘kotlin-parcelize’

but still it didn’t work for me, can someone help me. i have seen im in medium that’s I supposed to put , what I should to do?

This is the xml code

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#eef4fb"
    tools:context=".SplashActivity">

    <TextView
        android:id="@+id/app_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:elevation="2dp"
        android:fontFamily="@font/bungee"
        android:text="@string/app_name"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="50sp"
        app:layout_constraintEnd_toEndOf="0"
        app:layout_constraintStart_toStartOf="0"
        app:layout_constraintTop_toBottomOf="@+id/lottie" />

    <com.airbnb.lottie.LottieAnimationView
        android:id="@+id/lottie"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:elevation="2dp"
        app:layout_constraintBottom_toBottomOf="0"
        app:layout_constraintEnd_toEndOf="0"
        app:layout_constraintStart_toStartOf="0"
        app:layout_constraintTop_toTopOf="0"
        app:layout_constraintVertical_bias="0.1"
        app:lottie_autoPlay="true"/>

</androidx.constraintlayout.widget.ConstraintLayout>

This is the Java file

package com.allforus.bookclub;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;

@SuppressLint("CustomSplashScreen")
public class SplashActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_main);
    }
}

This is the build.gradle file


plugins {
    id 'com.android.application'
}

android {
    compileSdk 32

    defaultConfig {
        applicationId "com.allforus.bookclub"
        minSdk 26
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }


    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.4.2'
    implementation 'com.google.android.material:material:1.6.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation "com.airbnb.android:lottie:2.8.0"
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

Solution

in the xml file in bolow properties , use parent instead of 0

app:layout_constraintEnd_toEndOf="0"
app:layout_constraintStart_toStartOf="0"

app:layout_constraintBottom_toBottomOf="0"
app:layout_constraintEnd_toEndOf="0"
app:layout_constraintStart_toStartOf="0"
app:layout_constraintTop_toTopOf="0"

Answered By — RahulK

Понравилась статья? Поделить с друзьями:
  • Aapt error is incompatible with attribute background attr reference color
  • Aapt error file failed to compile
  • Aapt error failed to read png signature file does not start with png signature
  • Aae error 9178 was encountered
  • A start job is running for dev disk by как исправить