居中按钮或图像
答
很难说,不知道你有什么。但是,如果您查看文档,则每个xml attribute
在Java中都有相关的方法。例如,Look at the View Docs,您可以看到一个列表attributes
及其相应的Java方法和实际内容的描述。你应该能够使用它来让你开始,然后你可以用你尝试过的代码,你正在遇到的确切问题以及你可能得到的任何错误信息来提问。祝你好运!
答
使用代码来居中你的东西,而不是XML
文件中的属性。
中心按钮:
使用FlowLayout
。这将保持按钮在容器中水平居中,但不垂直。
JButton button = new JButton("Click Me!");
panel.setLayout(new FlowLayout(FlowLayout.CENTER));
panel.add(button);
如果你想在两个方向集中,你可以使用BoxLayout
。
JButton button = new JButton("Click Me!");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(Box.createVerticalGlue());
panel.add(button);
panel.add(Box.createVerticalGlue());
中心图像:
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
int xCenter = (this.getWidth() - image.getWidth())/2;
int yCenter = (this.getHeight() - image.getHeight())/2;
g2d.drawImage(image, xCenter, yCenter, null);
}
答
你试过:
Button button = new Button(getApplicationContext());
button.setLayoutParams(newLayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
button.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);