在发布模式下运行时,Android按钮ImageButton不显示图像

问题描述 投票:1回答:2

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

enter image description here

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

enter image description here

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

    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在调试和释放模式下两个按钮都显示相同的图像,这是预期的行为。

enter image description here

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

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

        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
2个回答
0
投票

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

另请参阅https://stackoverflow.com/a/50703322/1489726


0
投票

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

Android不允许处于发布模式的应用占用太多资源。我建议您使用Picasso之类的库在ImageButton上设置图像资源。毕加索将处理屏幕和按钮本身的资源大小调整。

而且也非常容易使用。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.