主要用到的类方法是view类下的layout,layout定义当前控件的左上角相对父节点的左上右下的距离。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(dm);
final int width = dm.widthPixels;
final int height = dm.heightPixels;
final ImageView iv = (ImageView) this.findViewById(R.id.iv);
iv.setOnClickListener(new OnClickListener() {
Random random = new Random();
public void onClick(View v) {
int l = random.nextInt(width);
int t = random.nextInt(height);
int ivWidth = iv.getMeasuredWidth();
int ivHeight = iv.getMeasuredHeight();
if (l > width - ivWidth) {
l = width - ivWidth;
}
if (t > height - ivHeight - 50) {
t = height - ivHeight - 50;
}
Log.v("btn l,t:", "" + l + "," + t);
iv.layout(l, t, l + ivWidth, t + ivHeight);
}
});
资源文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:andro />
</RelativeLayout>