View常用属性
- android:id="@+id/user"
- android:background=" "
- android:padding=“16dp” //设置间距
- android:layout_width=“wrap_content” //还可以设置fill_parent match_parent
- android:layout_height=“wrap_content”
XML文件位置
- 在Android res/layout目录下
- setContentView(R.layout.activity_main);
Java和XML控制UI
1.XML
-
将布局改为GridLayout
-
添加属性
android:id="@+id/layout" android:orientation="horizontal" android:rowCount="3" android:columnCount="4"
2.Java
//设置图片显示ImageView
private ImageView[] img=new ImageView[12];
//设置图片源:在R.mipmap.
private int[] imagePath=new int[]{
R.mipmap.img1, R.mipmap.img2, R.mipmap.img3, R.mipmap.img4,
R.mipmap.img5, R.mipmap.img6, R.mipmap.img7, R.mipmap.img8,
R.mipmap.img9, R.mipmap.img10, R.mipmap.img11, R.mipmap.img12,
};
//获取一个GridLayout布局空间
GridLayout layout=findViewById(R.id.layout);
for(int i=0;i<imagePath.length;i++){
img[i]=new ImageView(MainActivity.this);
img[i].setImageResource(imagePath[i]);
//设置间距
img[i].setPadding(2,2,2,2);
//LayoutParams主要用来动态控制子view的摆放位置
//参考https://www.jianshu.com/p/035f955d026b介绍
ViewGroup.LayoutParams params=new ViewGroup.LayoutParams(1920/4,1080/4);
img[i].setLayoutParams(params);
layout.addView(img[i]);
}