以编程方式定位 Android 按钮位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3228248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android Button Position Programmatically
提问by Paresh Mayani
I have a button in my application. I want to change its position programmatically. I have created a button in XML as follows:
我的应用程序中有一个按钮。我想以编程方式改变它的位置。我在 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>
Suppose I want to set the position of the button as 100px from left (as layout_marginLeft="100px"). How can I do it programmatically? Please help me to solve the problem.
假设我想将按钮的位置设置为距左侧 100 像素(如 layout_marginLeft="100px")。我怎样才能以编程方式做到这一点?请帮我解决问题。
回答by Leo
Luke, use the
卢克,使用
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);
回答by Pentium10
You need to get the view and transform into a Java object, then call setPadding
on it.
您需要获取视图并转换为 Java 对象,然后调用setPadding
它。
some thing like this would work out
像这样的事情会解决
Button myBtn;
myBtn = (Button) findViewById(R.id.Button01);
myBtn.setPadding(0,100,0,0);
Read more here: https://developer.android.com/reference/android/view/ViewGroup.MarginLayoutParams.html
在此处阅读更多信息:https: //developer.android.com/reference/android/view/ViewGroup.MarginLayoutParams.html
回答by Arun
You can't use setMargin()
with btn, use it with LayoutParams and then btn.setLayoutParams(params);
您不能setMargin()
与 btn 一起使用,请与 LayoutParams 一起使用,然后btn.setLayoutParams(params);
回答by Hasan A Yousef
With Kotlin
you can use the below:
有了Kotlin
您可以使用以下:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btnTag = Button(this).apply {
text = "Done"
setOnClickListener { finish() }
}
// btnTag.setOnClickListener { this.finish() }
val lp = RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT).apply {
addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
}
main_layout.addView(btnTag, lp)
}
Note: The layout should be RelativeLayout
注意:布局应该是 RelativeLayout