如果我扩展 Activity,ImageView 保持为空,但如果我扩展 AppCompatActivity,ImageView 将按预期工作

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

我不确定为什么我无法使用 ImageView 在我的应用程序中显示图像。有任何想法吗?请询问您是否需要更多信息。谢谢!

在我的 activity_main.xml 我有:

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

也许内容无关紧要。在我的 MainActivity 中,我有 public class MainActivity extends Activity { 然后图像不会打印,也不会记录任何错误。如果我将其更改为 public class MainActivity extends AppCompatActivity {,则图像会按预期打印在屏幕上。图片为矢量图。

我还有其他矢量图像,我在 settings/preferences 中用作 android:icon,它们似乎工作正常。

我的build.gradle如下:

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'
}

如果布局文件包含不起作用的行,因为它们需要例如不同的 API 级别,然后它们将被忽略,代码编译并且应用程序运行。或多或少。

如果您的 MainActivity 扩展 Activity,则布局中的以下行将不适用。

app:srcCompat="@drawable/armas_barcode"

这是因为 app 命名空间 (xmlns:app="http://schemas.android.com/apk/res-auto") 仅适用于 AppCompatActivity.

但您也可以像这样为 ImageView 设置可绘制资源:

android:src="@drawable/armas_barcode"