Android Button Position Programmatically

2020-07-06 07:52发布

问题:

I have a button in my application. I want to change its position programmatically. I have created a button in XML as follows:

<?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.

回答1:

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);


回答2:

You need to get the view and transform into a Java object, then call setPadding on it.

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



回答3:

You can't use setMargin() with btn, use it with LayoutParams and then btn.setLayoutParams(params);



回答4:

With Kotlin you can use the below:

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