我的应用程序中有一个按钮。我想以编程方式更改其位置。我在 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>
假设我想将按钮的位置设置为距左侧 100px(如 layout_marginLeft="100px")。我怎样才能以编程方式做到这一点?请帮助我解决问题。
最佳答案
卢克,使用
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);
关于以编程方式定位 Android 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3228248/