2013-04-03 61 views
1

我正在使用Eclipse爲Android創建應用程序。我知道你在XML文件中設置了諸如居中按鈕或圖像等屬性,但是如何在Java中執行此操作?居中按鈕或圖像

回答

0

很難說,不知道你有什麼。但是,如果您查看文檔,則每個xml attribute在Java中都有相關的方法。例如,Look at the View Docs,您可以看到一個列表attributes及其相應的Java方法和實際內容的描述。你應該能夠使用它來讓你開始,然後你可以用你嘗試過的代碼,你正在遇到的確切問題以及你可能得到的任何錯誤信息來提問。祝你好運!

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); 
} 
0

你試過:

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