居中按钮或图像

时间:2013-04-03 22:42:26

标签: java android button attributes

我正在使用Eclipse为Android创建应用。我知道你在XML文件中设置了诸如居中按钮或图像之类的属性,但是如何在Java中执行此操作?

3 个答案:

答案 0 :(得分:0)

在不知道你拥有什么的情况下很难说。但是,如果查看文档,每个xml attribute都有一个Java相关方法。例如,Look at the View Docs您可以看到attributes的列表及其对应的Java方法以及它实际执行的内容的描述。您应该能够使用它来帮助您入门,然后您可以使用您尝试过的代码,您遇到的确切问题以及您可能收到的任何错误消息提出问题。祝你好运!

答案 1 :(得分:0)

使用代码来集中您的内容,而不是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); 
}

答案 2 :(得分:0)

你试过了吗?

Button button = new Button(getApplicationContext());
button.setLayoutParams(newLayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
button.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);