Search code examples
androidxmlandroid-imageview

ImageView stays empty if I extend Activity but works as expected if I extend AppCompatActivity


I am not sure why I am not able to show images in my app using ImageView. Any ideas? Please ask if you need more information. Thanks!

In my activity_main.xml I have:

<ImageView
            android:id="@+id/imageView2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:srcCompat="@drawable/armas_barcode" />

Perhaps the contents are irrelevant. In my MainActivity I have public class MainActivity extends Activity { then the image is not printed and no errors are logged. If I change it to public class MainActivity extends AppCompatActivity { then image is printed on screen as expected. The image is a vector image.

I have other vector images which I use in settings/preferences as android:icon and they seem to work fine.

My build.gradle is as folllows:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.zebget.pricemap"
        minSdkVersion 25
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:design:27.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

Solution

  • If a layout file contains lines which do not work because they require e.g. a different API level, then they are simply ignored, the code compiles and the app works. More or less.

    If your MainActivity extends Activity, then the following line in the layout will not be applicable.

    app:srcCompat="@drawable/armas_barcode"

    This is because the app namespace ( xmlns:app="http://schemas.android.com/apk/res-auto") only works with an AppCompatActivity.

    But you can also set the drawable resource for your ImageView like this:

    android:src="@drawable/armas_barcode"