本文爲大家分享了Android動態佈局的實現代碼,供大家參考,具體內容如下
內容如下:介紹多種實現動態佈局的方法,以及如何用代碼來調整View位置
這裏只介紹三種佈局情況(注意不是方式)
1、無xml : 一個父類佈局包含一個子父類佈局,子父類佈局中包含ImageView
2、無xml : 只有一個父類佈局包含一個ImageView
3、有xlm佈局: 通過佈局ID 來進行動態佈局添加
總結了下其實步驟如下:
無xml佈局:
1、setContentView()之前new一個需要的佈局layout,再將layout放入setContentView()
2、new 出需要的控件設置好參數(id、text···)
3、new LayoutParams 設置好控件的大小、位置屬性(這裏感覺和xml設置控件屬性是一樣的)
4、最後將params和控件放入之前new的layout即可
有xml佈局:
1、setContentView()和以前一樣放入layout.xml
2、通過findViewById()找到要進行添加的佈局控件
之後的步驟和無xml佈局的2、3、4一樣
代碼如下:
1、無xml : 一個父類佈局包含一個子父類佈局,子父類佈局中包含ImageView
RelativeLayout relativeLayout = new RelativeLayout(this);
setContentView(relativeLayout);
ImageView imageView = new ImageView(this);
imageView.setId(2);
imageView.setImageResource(R.mipmap.ic_launcher);
//params 可以理解爲 imageView的位置、大小參數集合
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
relativeLayout.addView(imageView,params);
2、無xml : 只有一個父類佈局包含一個ImageView
RelativeLayout relativeLayout = new RelativeLayout(this);
setContentView(relativeLayout);
ImageView imageView = new ImageView(this);
imageView.setId(2);
imageView.setImageResource(R.mipmap.ic_launcher);
//params 可以理解爲 imageView的位置、大小參數集合
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
relativeLayout.addView(imageView,params);
3、有xlm佈局: 通過佈局ID 來進行動態佈局添加
private LinearLayout mLinearLayout;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
mLinearLayout = (LinearLayout) findViewById(R.id.linear_layout);
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.mipmap.ic_launcher);
imageView.setId(31);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(150, 80, 10, 0);
mLinearLayout.addView(imageView, params);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linear_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>