Java – how to set setlayoutparams on dynamically adding elements on a widget

Currently, I am dynamically adding elements to my widget using the following:

RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_design);

RemoteViews newView = new RemoteViews(context.getPackageName(), R.layout.widget_item);
views.addView(R.id.view_container, newView);

But how to dynamically add margins, weights and other attributes to the added elements?

At present, I have tried (using the code I found from different websites):

LinearLayout item = (LinearLayout) ((Activity) context).findViewById(R.id.widgetItem);
MarginLayoutParams marginParams = new MarginLayoutParams(item.getLayoutParams());
marginParams.setMargins(10, 50, 4, 5);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(marginParams);
item.setLayoutParams(layoutParams);

But this power is turned off

Of logcat:

resolvent:

LinearLayout layoutParams = item.getLayoutParams();
layoutParams.setMargins(10, 50, 4, 5);
item.setLayoutParams(layoutParams);

Creating new layoutparams in some way will always lead to such errors. I think there are still some fields that are not set. Only copy the existing ones

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>