以编程方式定位 Android 按钮

标签 android android-widget

我的应用程序中有一个按钮。我想以编程方式更改其位置。我在 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/

相关文章:

android - 如何将 ShowCaseView v5 构建器与 fragment 一起使用?

java - 使用 Libgdx 写入和读取 JSON

Android EditText inputType ="none"不起作用,变为 "textMultiLine"

android - 如何在现有 View 上叠加图标图像

Android Studio 3.4 似乎卡在了 transformClassesAndResourcesWithR8 上

android - PouchDB 与 Ionic 和应用程序更新

Android 我想裁剪尺寸为 500*500 的图像,它适用于除三星之外的所有设备

Android添加css文件

android - 我们如何设置列的内容以在表格布局中换行

android - 按下按钮 android