主要用到的类方法是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>

相关文章:

  • 2021-08-16
  • 2022-01-06
  • 2021-06-07
  • 2022-12-23
  • 2022-12-23
  • 2021-09-24
  • 2021-11-03
  • 2022-12-23
猜你喜欢
  • 2021-08-11
  • 2021-10-11
  • 2022-01-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案