如何以编程方式更改 Android 小部件按钮的样式?

发布于 2025-01-03 08:22:14 字数 111 浏览 2 评论 0原文

我想完全以编程方式更改 Android 小部件按钮(特别是角)的样式。意思是,我想在没有任何 xml 文件的情况下完成它。根据我的研究,我得出的结论是这是不可能的。我的结论正确吗?或者有人知道如何做到这一点?

I would like to change the style of an Android widget button (specifically the corners) completely programmatically. Meaning, I would like to do it without any xml files at all. From my research I am coming to the conclusion that this is not posible. Is my conclusion correct or does someone know how it might be done?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

当梦初醒 2025-01-10 08:22:14

您应该查看从 TextView 和 Button 视图继承的方法:

setPadding(int left, int top, int right, int bottom)

举个例子...您还可以更改按钮对象的布局参数,这使您可以访问通常可访问的所有 xml 属性。一般来说,您可以通过编程方式执行在 xml 中可以执行的所有操作。

如果这还不够,您可以扩展 Button 类并重写 onDraw 方法来更改 android 绘制按钮的方式

编辑:

也许您可以添加一个 xml 主题,就像这个线程建议的那样: 如何以编程方式在视图中设置样式属性

然后在其中设置

并以编程方式将主题添加到按钮?
我没有做过太多主题工作,所以我无法证明这是否一定有效

You should look at the inherited methods from TextView and View of Button:

setPadding(int left, int top, int right, int bottom)

to name one... you can also change the layoutparams of the button object, which gives you access to all the xml attributes normally accessible. In general, you can do everything programmatically that you can do in the xml.

If that isn't enough, you can extend the Button class and override the onDraw method to change how android draws your button

EDIT:

Maybe you can add an xml theme much like this thread suggests: How to programmatically setting style attribute in a view

and then in it set

and add the theme programmatically to the button?
I haven't done much work with themes, so I can't attest to whether this will definitely work

等风来 2025-01-10 08:22:14

您认为为什么会出现这种情况?以您的一项为例,这里有一种方法 设置填充

对于拐角,您可以使用具有圆角形状的可绘制对象。请参阅可绘制对象文档。 StackOverflow 上也有许多关于此的问题(带有答案) 。如果您想以编程方式执行此操作,可以使用 RoundedRectShape

Why do you think this is the case? Taking one of your items as an example, here's a method to set padding.

For corners you can use a drawable with a shape with rounded corners. See the documentation for drawables. There are also many questions (with answers) on StackOverflow about this too. If you want to do it programmatically there is the RoundedRectShape.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文