Android - 如何以编程方式更改 ImageButton 的宽度?
我有一个图像按钮。代码是 -
ImageButton shareButton = new ImageButton(this);
shareButton.setBackgroundResource(android.R.drawable.ic_menu_share);
RelativeLayout.LayoutParams shareParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
shareParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, navigationLogo.getId());
shareButton.setLayoutParams(shareParams);
我需要改变它的宽度。但是 ImageButton 和布局参数中都没有 setWidth 方法。网上查了很多都没有答案。
I have an ImageButton. The code is -
ImageButton shareButton = new ImageButton(this);
shareButton.setBackgroundResource(android.R.drawable.ic_menu_share);
RelativeLayout.LayoutParams shareParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
shareParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, navigationLogo.getId());
shareButton.setLayoutParams(shareParams);
I need to change its width. But there is no setWidth method in both ImageButton as well as the layout params. Looked a lot online without an answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用实际数字,而不是使用relativelayout.WRAP_CONTENT作为宽度,该数字将是按钮的新宽度(以像素为单位)。由于您可能希望将 dp 中的宽度指定为与分辨率无关,因此您可能需要使用如下方法将 dp 转换为像素:
Instead of using the RelativeLayout.WRAP_CONTENT for the width, you can use an actual number, which will be the new width of the button in pixels. Since you probably want to specify the width in dp to be resolution-independent, you will probably need to convert dp to pixels, with a method such as the following:
试试这个。
Try this.