I am trying to generate a button programatically in the center of the current view (which is the whole screen in this case). I get the screen height and width then find the center of the screen. Then I try to use the LayoutParams to set the top and left margins, taking into account the button size - but the result is not centered. What am I doing wrong?
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);
}
Try the following:
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams)myButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
myButton.setLayoutParams(layoutParams);
This way you don't need to explicitly define the margins.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments