Android以编程方式设置xml文件中声明的按钮边距?

Has*_*y31 2 java android

可能重复:
以编程方式在LinearLayout中设置边距

我的布局中有一堆小部件.我在布局文件中设置了layout_marginTop,但我想在活动中调用这两个按钮并设置layout_marginLeft并以编程方式更改值.我尝试使用getLayoutParams()但无法设置边距.是否有可能以编程方式更改在xml文件中声明的小部件的边距(在活动中调用布局后)?

// oncreate方法

setContentView(R.layout.gamelayout);
Run Code Online (Sandbox Code Playgroud)

// xml布局

    <ImageView
        android:id="@+id/gameImage"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
     >
    </ImageView>

    <Button
        android:id="@+id/lButton"
        android:layout_width="wrap_content"
        android:layout_height="140dip"
        android:layout_marginTop="10dip"
        android:layout_gravity="center_vertical|center_horizontal" />

    <Button
        android:id="@+id/rButton"
        android:layout_width="wrap_content"
        android:layout_height="140dip"
        android:layout_marginTop="10dip" 
        android:layout_gravity="center_vertical|center_horizontal" />

    <ImageView
        android:id="@+id/levelImage"
        android:layout_width="60dip"
        android:layout_height="60dip"
        android:layout_gravity="bottom|left"
        android:src="@drawable/ic_launcher" />

    <Button
        android:id="@+id/homeButton"
        android:layout_width="60dip"
        android:layout_height="60dip"
        android:layout_gravity="bottom|right"
        android:background="@drawable/home_btn" />
</FrameLayout>
Run Code Online (Sandbox Code Playgroud)

请帮我

谢谢

And*_*kov 6

Android中的每个布局都有自己的通用子类ViewGroup.LayoutParams,您应该使用它来设置窗口小部件的布局参数.在你的情况下它是FrameLayout.LayoutParams.

所以其他人提到:

FrameLayout layout = (FrameLayout) findViewById(R.layout.frame_layout);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( 
            FrameLayout.LayoutParams.FILL_PARENT, 
            FrameLayout.LayoutParams.WRAP_CONTENT); 
params.setMargins(30, 10, 0, 0); 
Button btn = (Button) findViewById(R.id.rbutton);
btn.setLayoutParams(params);
btn.requestLayout();
Run Code Online (Sandbox Code Playgroud)

另请参阅以下文档setMargins:

需要调用requestLayout(),以便考虑新的边距.