如何在现有布局中用 Java 代码创建 ImageView?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2994494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I create an ImageView in java code, within an existing Layout?
提问by Dan T
I'm looking for an easy way for the user to see how many drinks they've had for a BAC calculator.
我正在寻找一种简单的方法,让用户可以通过 BAC 计算器查看他们喝了多少酒。
Picture of the app:
应用程序图片:
On button press, I would like an image to be added to the screen, directly under the spinner and with left alignment. When I press the button again, I want another image to be added to the screen.
按下按钮时,我希望将图像添加到屏幕上,直接在微调器下方并左对齐。当我再次按下按钮时,我希望将另一个图像添加到屏幕上。
So if I pressed the add beer button, a drawable of a beer would appear below the spinner. If I pressed the add beer button again, I want there to be TWO drawables of beers under the spinner, preferably with them being added from the right.
因此,如果我按下添加啤酒按钮,啤酒的可绘制对象将出现在微调器下方。如果我再次按下添加啤酒按钮,我希望在微调器下方有两个可绘制的啤酒,最好是从右侧添加它们。
(Also, having them reach their width limit, wrapping around, and starting again on the left, but below a full line, would be AWESOME)
(此外,让它们达到宽度限制,环绕并从左侧重新开始,但低于整行,会很棒)
I can't figure out how to do this. I assume adding a ImageView in code to a relative layout (because it needs to be positioned to the right) would be the best route, but if it's possible in xml I'd be more than happy to use that. Any help?
我无法弄清楚如何做到这一点。我认为在代码中将 ImageView 添加到相对布局(因为它需要定位到右侧)将是最好的路线,但如果可以在 xml 中使用,我会非常乐意使用它。有什么帮助吗?
采纳答案by Daniel Waechter
In the button's click callback, create an ImageView object, set the bottle image, and position it. For example (I'm assuming the names of your elements):
在按钮的点击回调中,创建一个 ImageView 对象,设置瓶子图像并定位它。例如(我假设你的元素的名称):
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.beerbottle);
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.RelativeLayout01);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
layoutParams.addRule(RelativeLayout.BELOW, R.id.ButtonRecalculate);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
relativeLayout.addView(imageView, layoutParams);
I haven't tested this, mind you, but it should give you a good start. You'll probably need to add other parameters to the ImageView and possibly to the LayoutParams to make it look good, plus tracking how many bottles are displayed, etc.
请注意,我还没有测试过这个,但它应该给你一个良好的开端。您可能需要将其他参数添加到 ImageView 并可能添加到 LayoutParams 以使其看起来不错,并跟踪显示的瓶子数量等。