【问题标题】:Android button ImageButton not displaying image when run in release modeAndroid按钮ImageButton在发布模式下运行时不显示图像
【发布时间】:2019-10-13 03:22:41
【问题描述】:

我正在尝试使用ImageButton 来显示资源,.png 作为可点击按钮。当我在调试中运行我的应用程序时,ImageButton 正确获取图像。

但是,当我在发布模式下运行应用程序时,ImageButton 不显示可绘制对象:

我以编程方式创建并填充我的ImageButtons:

    private void setupButtons() {

        FlexboxLayout layout = view.findViewById(R.id.telcosLayout);
        final Activity activity = getActivity(); 

        // Telcom is an enum
        for (final Telcom t : Telcom.values()) {
            ImageButton b = new ImageButton(activity);

            int id = getId(t.toString().toLowerCase().replace(" ", "_") + "_logo", R.drawable.class);
            Log.i(TAG, "id is " + id);
            b.setImageResource(id);

            layout.addView(b);

            b.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    scanButtonListener.onShowScanButton(t);
                }
            });

        }
    }

在发布模式下运行时我的日志输出是:

2019-10-13 11:07:49.500 25757-25757/? I/select telcome: id is 2131165284
2019-10-13 11:07:49.501 25757-25757/? I/select telcome: id is 2131165320

以下是在调试模式下运行应用程序的日志:

2019-10-13 11:12:22.575 26146-26146/com.glan.input I/select telcome: id is 2131165284
2019-10-13 11:12:22.583 26146-26146/com.glan.input I/select telcome: id is 2131165320

似乎在两种模式下都可以找到相同的可绘制对象,但由于某种原因,它们不会在发布模式下显示。怎么回事?

我已验证从drawable-ldpidrawable-xxxhdpi 的所有屏幕密度都存在可绘制对象。

我还发现,如果我根据日志行对b.setImageResource(2131165284); 进行硬编码,ImageButton 在调试和发布模式下都会为两个按钮显示相同的图像,这是预期的行为。

为什么动态设置资源在发布模式下不起作用?

编辑:好的,我想我找到了问题所在。我的发布构建模式具有以下属性:

        release {
            minifyEnabled true
            shrinkResources true
            debuggable true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-project.txt'
            signingConfig = signingConfigs.release
        }

当我禁用shrinkResources 时,通过将其注释掉,图像再次出现。似乎,基于"minifyEnabled" vs "shrinkResources" - what's the difference? and how to get the saved space?,ProGuard 检测到我依赖的资源,.png 可绘制对象,因为它们是动态请求的,所以 shrinkResources 将它们完全删除。

有谁知道如何解决这个问题?

【问题讨论】:

    标签: android android-imagebutton


    【解决方案1】:

    好的,我找到了答案。对我有用的解决方案是使用https://developer.android.com/studio/write/tool-attributes#toolskeep 中的tools:keep 有目的地保留这些资源,即使shrinkResources 设置为true

    另见https://stackoverflow.com/a/50703322/1489726

    【讨论】:

      【解决方案2】:

      您是否检查过它是否因为图像占用过多资源而发生?图片文件有多大?它与按钮的尺寸相同吗?

      Android 不允许处于发布模式的应用占用如此多的资源。我建议您使用像 Picasso 这样的库来设置 ImageButton 上的图像资源。 Picasso 将处理屏幕资源大小和按钮大小本身的调整。

      而且它也很容易使用。

      Picasso.get().load(R.drawable.your_image_resource).into(yourImageButton);

      https://square.github.io/picasso/

      【讨论】:

        猜你喜欢
        • 2015-08-20
        • 1970-01-01
        • 2021-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-30
        • 2018-05-29
        相关资源
        最近更新 更多