以编程方式居中(在屏幕中)图像按钮的最佳方法是什么?

时间:2014-01-26 02:52:43

标签: android android-layout

我正在尝试以编程方式在当前视图的中心生成一个按钮(在这种情况下是整个屏幕)。我得到屏幕的高度和宽度,然后找到屏幕的中心。然后我尝试使用LayoutParams设置顶部和左边距,考虑按钮大小 - 但结果不居中。我做错了什么?

public class StartActivity extends Activity {

private int cScreenWidth;
private int cScreenHeight;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start);

    RelativeLayout ll = (RelativeLayout)findViewById(R.id.startLayout);

    Display display = getWindowManager().getDefaultDisplay(); 
    cScreenWidth = display.getWidth();  // deprecated but needed for API 10
    cScreenHeight = display.getHeight();  // deprecated but needed for API 10

    ImageButton myButton = new ImageButton(this);
    myButton.setId(100);
    myButton.setBackgroundResource(R.drawable.ic_launcher);

    int size = Math.min(cScreenWidth / 3, cScreenHeight / 3);
    LayoutParams lp = new LayoutParams( size, size );
    lp.leftMargin = (cScreenWidth / 2) - (size / 2);
    lp.topMargin = (cScreenHeight / 2) - (size / 2);
    ll.addView(myButton, lp);
}

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

RelativeLayout.LayoutParams layoutParams = 
    (RelativeLayout.LayoutParams)myButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
myButton.setLayoutParams(layoutParams);

这样您就不需要明确定义边距。