Suppose you want to place a button on a screen and you have divided the screen into 100x60 cells, with each cell measuring
8 pixels (800/100) along the horizontal axis and
8 pixels (480/60) along the vertical axis, considering that you are using a TAB with a
resolution of 800x480 pixels. In landscape mode, divide the width by 100 and the height by 60, while in portrait mode, the division factor will be vice versa. Please note that HTML tags should be retained.
现在您想放置一个宽度为35个单元格,高度根据其上的文本自适应的按钮,并将其放置在坐标20,20(x,y)单元格编号。我已经提供了一种实现此目的的方法。请注意:无论您以这种方式或使用此想法放置的任何视图,在多个显示分辨率上都将处于相同的位置,并具有相同的尺寸和外观。
放置按钮的方法
public void placeButton(int btnId, int xCordinate, int yCordinate, int btnWidth,
float fontSize, String btnTextColor, String btnBackgroundColor, String message){
try{
int currentApi = Build.VERSION.SDK_INT;
Button btn = new Button(context);
btn.setId(btnId);
btn.setText(message);
btn.setTextSize(TypedValue.COMPLEX_UNIT_PX, pixels_grid_X*fontSize);
if(btnTextColor != null)
{
btn.setTextColor(Color.parseColor(btnTextColor));
}
int widthInPixel = (int) (btnWidth*pixels_grid_X);
btn.setWidth(widthInPixel);
if(btnBackgroundColor != null)
{
if(currentApi >= 16){
btn.setBackground(new ColorDrawable(Color.parseColor(btnBackgroundColor )));
}
else
{
btn.setBackgroundDrawable(new ColorDrawable(Color.parseColor(btnBackgroundColor )));
}
btn.setOnTouchListener(this);
}
else
{
btn.setBackgroundResource(android.R.drawable.btn_default);
}
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
params1.leftMargin = (int) (xCordinate*pixels_grid_X);
params1.topMargin = (int) (yCordinate*pixels_grid_Y);
btn.setLayoutParams(params1);
layout.addView(btn,params1);
}catch(Exception ex){
ex.printStackTrace();
}
}