亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何用隨機圖像填充 gridLayout 8x8

如何用隨機圖像填充 gridLayout 8x8

千巷貓影 2022-10-26 16:54:02
我正在開發一種“糖果粉碎”,我需要的是當你打開應用程序時,元素(寶石)是隨機生成的。在 xml 中,我創建了一個 8x8 的“GridLayout”,它將存儲 6 個 ImageView,其中每個 ImageView 都是一個 gem。我正在考慮做的是從 .java 以某種方式通過 8x8 矩陣,我將元素隨機加載到我的 GridLayout 中。但我就是不知道該怎么做。如果你幫助我,我將不勝感激,我已經被困在這兩天了。謝謝。public class MainActivity extends AppCompatActivity {private int [] vector = new int[]{R.drawable.blue, R.drawable.green,R.drawable.yellow,R.drawable.red,R.drawable.purple,R.drawable.orange};private int num=6;@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    int matriz[][] = new int[8][8];    GridLayout grid = (GridLayout) findViewById(R.id.grid);    int numOfCol = grid.getColumnCount();    int numOfRow =  grid.getRowCount();    for (int x = 0; x <= numOfCol; x++) {        for (int y = 0; y <= numOfRow; y++) {            int numero = (int) (Math.random() * num) + 1;            grid.addView(grid, matriz[x][y]);        }    }<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_height="fill_parent"android:layout_width="fill_parent"android:columnCount="8"android:rowCount="8"android:orientation="horizontal"android:background="#053b13"android:id="@+id/grid"><ImageView    android:id="@+id/blue"    android:src="@drawable/blue"    android:layout_width="70dp"    android:layout_height="44dp"    android:onClick="gemas"></ImageView><ImageView    android:id="@+id/green"    android:src="@drawable/green"    android:layout_width="70dp"    android:layout_height="44dp"    android:onClick="gemas"></ImageView><ImageView    android:id="@+id/orange"    android:src="@drawable/orange"    android:layout_width="70dp"    android:layout_height="44dp"    android:onClick="gemas"></ImageView><ImageView    android:id="@+id/purple"    android:src="@drawable/purple"    android:layout_width="70dp"    android:layout_height="44dp"    android:onClick="gemas"></ImageView>
查看完整描述

1 回答

?
心有法竹

TA貢獻1866條經驗 獲得超5個贊

Java 代碼


Random rnd = new Random();

for(int c=0; i<grid.getChildCount();i++){

    int bg = vector[ rnd.nextInt(vector.length) ];


    grid.getChildAt(c).setBackgroundResource(bg);

}

注意:我是用 Kotlin 編寫的,Java 代碼來自內存。如果您發現錯誤,請發表評論。


科特林代碼:


val vector = intArrayOf(

        R.mipmap.ic_launcher,

        R.mipmap.ic_launcher_round

)


for (c in 0 until grid.childCount) {


    grid.getChildAt(c).backgroundResource = vector[Random.nextInt(vector.size)]


}

結果

http://img1.sycdn.imooc.com//6358f5cf00015b4704000285.jpg

查看完整回答
反對 回復 2022-10-26
  • 1 回答
  • 0 關注
  • 79 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號