场景
效果
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。
实现
新建Android项目,首先打开activity_main.xml
使用XML设置页面
将其布局改为GridLayout,并设置其行数为3,列数为4,以及设置其id。
android:rowCount = "3" android:columnCount = "4" android:id="@+id/gridLayout"
使用Java代码设置页面
首先将要显示的照片复制到res/drawale下
原本要显示12张,应该要复制12张照片,这里只复制了一张。
打开MainActivity.java
先声明一个ImageView数组和图片路径数组。
private ImageView[] img = new ImageView[12]; private int[] imagePath = new int[]{ R.drawable.img1,R.drawable.img1,R.drawable.img1,R.drawable.img1, R.drawable.img1,R.drawable.img1,R.drawable.img1,R.drawable.img1, R.drawable.img1,R.drawable.img1,R.drawable.img1,R.drawable.img1 };
然后在其OnCreate方法中
//获取layout GridLayout layout = (GridLayout) findViewById(R.id.gridLayout); for(int i =0;i<imagePath.length;i++) { img[i] = new ImageView(MainActivity.this); //给ImageView设置图片源 img[i].setImageResource(imagePath[i]); //设置内边距 img[i].setPadding(2, 2, 2, 2); //设置布局参数 即图片 大小 ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(240,140); img[i].setLayoutParams(params); //将ImgageView添加到layout上 layout.addView(img[i]);
完整示例代码
package com.badao.layouttest; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.ViewGroup; import android.widget.GridLayout; import android.widget.ImageView; public class MainActivity extends AppCompatActivity { private ImageView[] img = new ImageView[12]; private int[] imagePath = new int[]{ R.drawable.img1,R.drawable.img1,R.drawable.img1,R.drawable.img1, R.drawable.img1,R.drawable.img1,R.drawable.img1,R.drawable.img1, R.drawable.img1,R.drawable.img1,R.drawable.img1,R.drawable.img1 }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //获取layout GridLayout layout = (GridLayout) findViewById(R.id.gridLayout); for(int i =0;i<imagePath.length;i++) { img[i] = new ImageView(MainActivity.this); //给ImageView设置图片源 img[i].setImageResource(imagePath[i]); //设置内边距 img[i].setPadding(2, 2, 2, 2); //设置布局参数 即图片 大小 ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(240,140); img[i].setLayoutParams(params); //将ImgageView添加到layout上 layout.addView(img[i]); } } }
原文地址:https://www.cnblogs.com/badaoliumangqizhi/p/12147534.html
时间: 2024-10-11 04:12:28