2010-07-12 42 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);