注:java
博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公衆號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。 android
新建Android項目,首先打開activity_main.xml編程
將其佈局改成GridLayout,並設置其行數爲3,列數爲4,以及設置其id。數組
android:rowCount = "3" android:columnCount = "4" android:id="@+id/gridLayout"
首先將要顯示的照片複製到res/drawale下app
本來要顯示12張,應該要複製12張照片,這裏只複製了一張。ide
打開MainActivity.java佈局
先聲明一個ImageView數組和圖片路徑數組。this
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方法中spa
//獲取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]);
完整示例代碼.net
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]); } } }