安卓:如何编程中心创建的按钮? [英] Android: how to center a button programatically created?

查看:99
本文介绍了安卓:如何编程中心创建的按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以编程方式创建一个按钮,并把它集中在布局,水平和垂直。我想用下面的code:

I need to create a button programatically and have it centered on the layout, both horizontally and vertically. I am trying with the following code:

LinearLayout ll = (LinearLayout)findViewById(R.id.layoutItem);
Button b = new Button(this);        
b.setBackgroundDrawable(getResources().getDrawable(R.drawable.button));
b.setLayoutParams(new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT)); 
b.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
ll.addView(b);

但它不工作。按钮出来顶部所有左侧。

But it's not working. The button comes out on top all to the left.

关于如何解决这个任何线索?

Any clues on how to fix this?

非常感谢。

推荐答案

我会做这样的事情:

LinearLayout.LayoutParams ll = (LinearLayout.LayoutParams)b.getLayoutParams();    
ll.gravity = Gravity.CENTER;
b.setLayoutParams(ll);

其是否正常工作。

see if that works.

这篇关于安卓:如何编程中心创建的按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆