2010-07-12 56 views
7

我的應用程序中有一個按鈕。我想以編程方式改變它的位置。我在XML創建了一個按鈕,如下所示:以編程方式安卓按鈕位置

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 

<Button android:text="@+id/Button01" 
     android:id="@+id/Button01" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginLeft="50px" 
     android:layout_marginTop="10px" 
     > 
</Button> 
</LinearLayout> 

假設我想從左邊設置按鈕的位置爲100像素(如layout_marginLeft =「100px的」)。我怎樣才能以編程方式做到這一點?請幫我解決問題。

+0

讓我來給點... 其實我的佈局,包含9個按鈕......所以一些按鈕有形和無形的基礎上,condition..so我要對齊(向左或向右移動)以編程方式...請幫助我 – 2010-07-13 05:02:24

+0

看看這個答案。它清楚地顯示瞭如何設置按鈕的邊距。 http://stackoverflow.com/a/4594374/525541 – MindWire 2012-06-27 13:03:28

回答

3

填充和保證金是不一樣的...這是線程是你在找什麼 Set margins in a LinearLayout programmatically

+0

此鏈接對我有幫助...但我的佈局包含9個按鈕...所以有些是可見和不可見的基礎上的條件..所以我想對齊(向左或向右)它以編程方式...請幫助我 – 2010-07-13 05:01:13

+1

你注意到,除了可見,不可見也隱藏選項的視圖可見性http://developer.android.com/reference/android/view/View.html#GONE。這取決於計劃做什麼,但一個乾淨的解決方案將只是爲了對齊你的按鈕在XML和當你不需要他們設置可見性消失。如果這沒有幫助,請提供更多信息,以便我們幫助您。 – 2010-07-13 12:09:59

+0

也有同樣的問題。試過View.INVISIBLE和它的完美。感謝@MojoRisin – j2me 2012-04-18 08:10:47

6

您需要獲取視圖並轉換爲Java對象,然後調用setPadding

一些像這樣的事情會制定出

Button myBtn; 
myBtn = (Button) findViewById(R.id.Button01); 
myBtn.setPadding(0,100,0,0); 

在這裏閱讀更多: https://developer.android.com/reference/android/view/ViewGroup.MarginLayoutParams.html

+0

其不工作..在setMargins函數下顯示紅線(錯誤)。 我正在使用Android 1.5 – 2010-07-12 12:48:14

+0

嘗試setPadding。 – Pentium10 2010-07-12 12:55:05

+0

我也試過 btnTest.setPadding(100,0,0,0);但它使100寬度和文本的按鈕右側顯示,但仍然不工作 – 2010-07-12 13:01:32

2

您不能使用setMargin()與btn,與LayoutParams一起使用,然後btn.setLayoutParams(params);

7

盧克,使用

RelativeLayout.LayoutParams rel_btn = new RelativeLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 

rel_btn.leftMargin = myXPosition; 
rel_btn.topMargin = myYPosition; 
rel_btn.width = buttonW; 
rel_btn.height = buttonH; 

myButton.setLayoutParams(rel_btn);