设置控件的随机显示位置 setlayoutparams

RelativeLayout.LayoutParams parms=(RelativeLayout.LayoutParams)img.getLayoutParams();
parms.leftMargin = (int) (Math.random() * 320);
parms.topMargin = (int) (Math.random() * 480);
         
img.setLayoutParams(parms);       
img.invalidate();

 

 

private RelativeLayout.LayoutParams getOtherSetLayoutParameter() { int height =190; int width = 310; DisplayMetrics dm=getResources().getDisplayMetrics(); if(dm.densityDpi == DisplayMetrics.DENSITY_HIGH){ height = height*DisplayMetrics.DENSITY_HIGH/DisplayMetrics.DENSITY_MEDIUM; width = width*DisplayMetrics.DENSITY_HIGH/DisplayMetrics.DENSITY_MEDIUM; } else if(dm.densityDpi == DisplayMetrics.DENSITY_LOW){ height = height*DisplayMetrics.DENSITY_LOW/DisplayMetrics.DENSITY_MEDIUM; width = width*DisplayMetrics.DENSITY_LOW/DisplayMetrics.DENSITY_MEDIUM; } RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(width, height); int screenWidth=dm.widthPixels; int screenHeight=dm.heightPixels; lp.topMargin = screenHeight/2-height/2; lp.leftMargin = screenWidth/2-width/2; return lp; }

XXX.addView(mOthersetModeLayout,getOtherSetLayoutParameter());

 

把上面的代码精简一下:

private RelativeLayout.LayoutParams getOtherSetLayoutParameter() {
                RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(310, 248);
                lp.addRule(RelativeLayout.CENTER_IN_PARENT);
                return lp;
}

你可能感兴趣的:(设置控件的随机显示位置 setlayoutparams)