在Android和iPhone上的Button控件间距不同的问题,可以在XML布局文件中针对不同的平台设置间距的数值。首先需要得到Android和iPhone的设备信息,然后根据设备信息动态设置布局文件中Button控件的间距属性值。示例代码如下:
DisplayMetrics metrics = getResources().getDisplayMetrics();
int densityDpi = metrics.densityDpi;
if (densityDpi == DisplayMetrics.DENSITY_HIGH) {
// Set button margin for iPhone
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(20, 0, 20, 0); // left, top, right, bottom
Button btn1 = (Button) findViewById(R.id.btn1);
btn1.setLayoutParams(params);
} else if (densityDpi == DisplayMetrics.DENSITY_XHIGH) {
// Set button margin for Android
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(30, 0, 30, 0); // left, top, right, bottom
Button btn1 = (Button) findViewById(R.id.btn1);
btn1.setLayoutParams(params);
}
此代码会根据不同的设备密度设置指定的按钮间距。