man*_*ore 15 android position android-layout
我正在研究android api8.我想动态地在屏幕上定位/放置视图.但要使用setX和setY,我们需要API等级11及以上.我们如何在API 8中使用它,或者有什么替代方案吗?需要帮忙
Leo*_*die 30
你可以使用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);
Run Code Online (Sandbox Code Playgroud)
请注意,LayoutParams的类型必须等于要将其添加到的子视图的父级.(LinearLayout.LayoutParams对于一个LinearLayout,RelativeLayout.LayoutParams为一个RelativeLayout等).
此外,当项目添加到父容器时,childView.setLayoutParams(params);您也可以使用它parentView.addView(childView,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;
}
Run Code Online (Sandbox Code Playgroud)