Android Button Position Programmatically

混江龙づ霸主 提交于 2019-12-04 03:11:56

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

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

Arun

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!