【发布时间】:2017-03-31 06:41:31
【问题描述】:
在 Android 中,我在 Java 代码中创建了一个 ImageView,并在将其添加到主布局(RelativeLayout)之前设置了它的布局参数:宽度、高度和上边距。宽度和高度已成功应用,但边距对图像视图位置没有任何影响。实际的上边距保持为 0。
如何将上边距应用于视图?代码如下。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initClouds();
}
private void initClouds() {
addCloud(R.drawable.cloud1, R.dimen.cloud1_top_margin);
addCloud(R.drawable.cloud2, R.dimen.cloud2_top_margin);
}
private void addCloud(int imageResId, int topMarginResId) {
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.mainLayout);
ImageView cloud = new ImageView(this);
int height = (int) getResources().getDimension(R.dimen.cloud_height);
int width = (int) getResources().getDimension(R.dimen.cloud_width);
ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(width, height);
params.topMargin = (int) getResources().getDimension(topMarginResId);
cloud.setImageResource(imageResId);
mainLayout.addView(cloud, params);
}
}
【问题讨论】:
-
你确定
getResources().getDimension(topMarginResId)返回的不是0吗? -
是的,它返回非零值。我已经记录了结果并得到了正确的值:topMargin=120 topMargin=30
标签: java android android-layout android-relativelayout margins