如何在Android小部件中将ImageView的高度和宽度动态设置为“ match_parent”?

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

我的主屏幕小部件中有一个ImageView。在布局文件中,我将高度和宽度设置为wrap_content。但是根据用户的输入,我必须将其高度和宽度更改为match_parent。如何做到这一点?

RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_layout);

现在我试图在此setInt()对象上使用RemoteViews方法来检查是否可以更改高度和宽度:

rv.setInt(R.id.widgetImageView, "setMinimumHeight", 300);

但是这就是我在logcat上得到的内容:

couldn't find any view, using error view
android.widget.ImageView can't use method with RemoteViews: setMinimumHeight(int)

那么如何将其高度和宽度更改为match_parent

android android-widget android-imageview
2个回答
1
投票

用途:

    ImageView view = new ImageView();
    view.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));

LayoutParams的第一个参数表示宽度,第二个参数表示高度。

这里,我创建了一个新的ImageView进行解释。您应该使用代码中的ImageView变量来完成上述操作。我希望这很清楚。

[更新为代码]:对不起,MATCH_PARENT变量在LayoutParams下,而不在View下。我已经更新了代码。

[更新]:以上答案不适用于RemoteViews,因为RemoteViews无法具有布局参数。根据此SO Question中给出的答案,无法通过常规方法设置或查找RemoteView的尺寸。

我找到了这个Android Widget Tutorial,在小部件大小部分下,作者说:

    A Widget will take a certain amount of cells on the homescreen. A cell is
    usually used to display the icon of one application. As a calculation rule 
    you should define the size of the widget with the formula: 

    ((Number of columns / rows)* 74) - 2. 

    These are device independent pixels and the -2 is used to avoid rounding issues.

    As of Android 3.1 a Widgets can be flexible in size, e.g. the user can make it
    larger or smaller. To enable this for Widgets you can use the 
    android:resizeMode="horizontal|vertical" attribute in the XML configuration file
    for the widget.

由此,我建议您不要直接设置特定的整数大小值,为什么不设置要调整大小的行数和列数呢?例如,如果您的初始窗口小部件大小为4 Columns and 1 Row,那么在用户输入时,您可以将其更改为4 Columns and 4 Rows,从而使其占据整个屏幕(窗口小部件的最大大小为4行和4列)

我知道上述方法不是您想要的,但这似乎是我的唯一方法。尝试看看是否有帮助。


0
投票

对于那些想知道如何实现的人,我在布局中使用了两个ImageView。一种将高度和宽度设置为wrap_content,另一种将高度和宽度设置为match_parent。根据用户的输入,我调用了setVisibility以隐藏通过ImageView不需要的RemoteView

rv.setInt(R.id.widgetImageView1, "setVisibility", View.GONE);

我们可以通过ImageView调用的RemoteView方法很少。

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