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

4

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

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

现在我尝试使用setInt()方法在这个RemoteViews对象上,就像这样简单地检查是否可以更改高度和宽度:
rv.setInt(R.id.widgetImageView, "setMinimumHeight", 300);

但这是我在日志中获得的内容:
couldn't find any view, using error view
android.widget.ImageView can't use method with RemoteViews: setMinimumHeight(int)

那么我该如何将其高度和宽度更改为match_parent呢?
2个回答

1
对于那些想知道如何实现这个的人,我在布局中使用了两个ImageView。一个高度和宽度设置为wrap_content,另一个高度和宽度设置为match_parent。根据用户的输入,我通过RemoteView调用setVisibility来隐藏不需要的ImageView
rv.setInt(R.id.widgetImageView1, "setVisibility", View.GONE);

有非常少的ImageView方法可以通过RemoteView调用。


4
可以使用专门的方法更轻松地改变RemoteViews中视图的可见性:rv.setViewVisibility(R.id.widgetImageView1, View.GONE) - Stanislav

-2

使用:

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

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

在这里,我为了解释创建了一个新的ImageView。你应该使用自己的代码中的ImageView变量来执行上述操作。我希望这很清楚。

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

[更新]: 上面的答案对于RemoteViews不起作用,因为RemoteViews不能有布局参数。根据SO问题中给出的答案,没有办法通过常规方法设置或查找远程视图的尺寸。

我发现了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列1行,那么在用户输入后,您可以将其更改为4列4行,从而使其占据整个屏幕(小部件的最大尺寸为4行4列)。
我知道上述方法可能不是您想要的,但在我看来,这似乎是唯一的方法。请尝试并查看是否有帮助。

3
不正确!我想要改变一个主屏幕小部件内的ImageView的高度和宽度。只能通过RemoteViews才能访问这个ImageView - Shubham
显然没有简单的方法来设置小部件的尺寸。请查看我的更新答案,我已经发布了一个教程链接,并提出了关于如何调整小部件大小的建议。 - sanjeev mk
我想要调整 ImageView 的大小,而不是整个小部件。 - Shubham
如何设置固定大小,例如50x50。 - MohammedAli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接