您可以通过使用LayoutParams来做到这一点。 可以将这些添加到android界面的组件中以设置其界限和位置。
一个例子(设置上的RelativeLayout的子视图的LayoutParams)
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //The WRAP_CONTENT parameters can be replaced by an absolute width and height or the FILL_PARENT option)
params.leftMargin = 50; //Your X coordinate
params.topMargin = 60; //Your Y coordinate
childView.setLayoutParams(params);
,请注意该的LayoutParams的类型必须等于要添加他们到childview的父。 (LinearLayout.LayoutParams对于LinearLayout,RelativeLayout.LayoutParams对于RelativeLayout等)。
此外,您也可以使用parentView.addView(childView,params);而不是childView.setLayoutParams(params);来设置项目添加到父容器时的Layoutparams。
注意!坐标值以像素为单位。因为它是使用DP值来定义你的界面大小的最佳实践,你可以使用这段代码DP转换为像素:
private int getPixels(int dipValue){
Resources r = getResources();
int px = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, r.getDisplayMetrics());
return px;
}