android實現布局重疊


主要用到的類方法是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:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="hello" />
<ImageView
android:id="@+id/iv"
android:src="@drawable/ic_launcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM