Java Android布局-设置相对于屏幕大小的圆角半径

Java Android布局-设置相对于屏幕大小的圆角半径,java,android,xml,layout,Java,Android,Xml,Layout,我使用以下内容作为布局的背景: <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#FFFFFF" /> <corners android:radius="20dip"/> <padding android:left

我使用以下内容作为布局的背景:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF" />
    <corners android:radius="20dip"/>
    <padding android:left="0dip" android:top="0dip" android:right="0dip" android:bottom="0dip" />
</shape>


但在4英寸800x480屏幕上,圆形度看起来与在4.7英寸1280x720屏幕上大不相同。有没有办法设置相对于屏幕的半径

这是一个好问题,我不知道用XML做这件事的好方法(如果使用dip值是不够的),但是您可以通过编程方式创建可绘制图形,并根据屏幕大小进行一些计算,以实现您想要的效果

// Create a drawable
GradientDrawable shape = new GradientDrawable();
// Get the screen size
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
// Do some math to get the radius value to scale
int radius = (int) Math.round(width * height / 100000);
// Set the corner radius
shape.setCornerRadius(radius);
// Apply shape as background
setBackground(shape);
因此,对于1280x800屏幕,这将是宽度*高度=1024000除以100000,四舍五入为10px半径。但是,在800x480屏幕上,半径为4px。但是,这并不考虑屏幕的物理尺寸,因此,如果这是一个问题,您可以获得以英寸为单位的物理尺寸:

DisplayMetrics dm = new DisplayMetrics();
display.getMetrics(dm);
double x = Math.pow(dm.widthPixels/dm.xdpi,2);
double y = Math.pow(dm.heightPixels/dm.ydpi,2);
double inches = Math.sqrt(x+y);
然后您还可以将该值作为因子,例如:

int radius = (int) Math.round(width * height * inches / 500000);
现在,对于1280x800 4“屏幕,这是宽度*高度*4=4096000除以500000四舍五入得到的半径为8px。对于800x480 10”屏幕,这是宽度*高度*10=4096000除以500000四舍五入得到的半径为8px


我知道这是一个肮脏的黑客,你可能需要调整数学使其完美缩放,但我相信这是缩放半径的唯一方法。

不。你没有%选项。dp(=dip)是解决阿瓦雷诺问题的最佳选择,希望这能有所帮助。