RemoteView setLayoutParams - 在 HomeScreen 小部件内更改 ImageView 大小

Bar*_*thy 2 android imageview remoteview

我的应用程序显示了一个小部件,共有 8 个按钮。我想让用户可以设置该小部件的样式并自定义按钮下方的 ImageViews 的大小。目的是让按钮保持原样,但动态更改 ImageView 大小。

为此,用户可以设置一个图标大小,它作为一个整数iconSize存储在 SharedPreference 中。

如何更改小部件中 ImageView 的大小?

现在,ImageViews 是使用 xml 文件中设置的大小创建的。如何使用其他尺寸实现重绘?

我认为这里没有太多代码可以发布,但如果有必要,我很乐意这样做,如果您知道哪些代码可以在这里提供帮助,请告诉我。

我不想做的事情:

  • 调整整个小部件的大小

  • 创建大量布局文件以根据 iconSize 进行切换

一些代码:

这就是我在活动中将 ImageView 大小设置为小部件预览的方式。icons是一个 ImageViews 数组,progress 指的是一个用于选择iconSize 的 ProgressBar

for (ImageView icon : icons) {
    icon.requestLayout();

    // convert into actual Pixels
    progress = (int) TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_PX,
            progress,
            getResources().getDisplayMetrics()
    );

    // set width and height
    icon.getLayoutParams().height = progress;
    icon.getLayoutParams().width = progress;

    sizeText.setText("" + progress);
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*thy 5

这是我发现的一个小解决方法:

简单地使用

views.setViewPadding(R.id.vieId, left, top, right, bottom);
Run Code Online (Sandbox Code Playgroud)

(视图 = 远程视图)

你只需要进行一些计算,这样的iconSize的100%(最大可能的大小)等于0填充和1%iconSize等于最大填充。

它也可以在没有的情况下工作,但我认为添加

android:cropToPadding="true"
Run Code Online (Sandbox Code Playgroud)

如果使用此方法,则属性为 ImageViews。

编辑:

我忘了提到在设置填充后的某个时候你应该更新小部件(当用户退出应用程序查看小部件时,我在onPause() 中这样做)。在Activity 中使用setPadding()也将导致没有在 View 上调用invalidate()以强制重绘/更新它。

这里有更多代码:

seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        // Map the values, 100 is the custom max of my seekBar
        // I am adding 1 to because the seekBar goes from 0-99,
        // but the size from 1% to 100%
        int iconSize  = 100 - (progress+1);

        for (ImageView icon : icons) {
            // set the padding
            icon.setPadding(iconSize, iconSize, iconSize, iconSize);

            // force the ImageView to redraw with the new padding, this
            // serves as a live preview of the icons' sizes.
            icon.invalidate();
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // you might want to do something here
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        // map the value
        int iconSize = 100 - (seekBar.getProgress()+1);

        // save it in your SharedPreferences or somewhere else
        Utils.setDefaultsInt(Con._ICONSIZE, iconSize, MainPage.this);
    }

});
Run Code Online (Sandbox Code Playgroud)