从数组

时间:2017-04-08 02:32:46

标签: android arrays drawable grid-layout

尝试为我的儿子构建一个应用程序(这仍然非常新)仍然尽可能快地阅读和学习。基本上我已经创建了一个测试应用程序,但我正在尝试填充gridlayout(这只是一个4x4网格真实应用程序将更大)当我点击一个按钮时从图像数组。我希望我可以随机化图像的顺序(这是我的下一个问题要搞清楚!)我无法将图像加载....

MainActivity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

//added new int[]
int[] pics = new int[]{R.drawable.e1, R.drawable.e2, R.drawable.e3,R.drawable.e4};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btnDisplay = (Button)findViewById(R.id.btnDisplay);
    btnDisplay.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.btnDisplay:

           setContentView(R.layout.activity_main);

            GridLayout grid = (GridLayout) findViewById(R.id.grid); //my grid
           // grid.removeAllViews(); //clears existing views..i think

            int items = 9; //number of items to dispaly in my grid
            int column = 3;
            int rows = 3;
            grid.setRowCount(rows);
            grid.setColumnCount(column);

          //  ImageView iv = new ImageView(this);
           // iv.setImageResource(pics[4]);

            //grid.addView(iv,1);

            ////*******************************************************
            //squares = new int[4];
            // Put the images in the GridLayout.
            for(int i = 0; i < 4; i++) {
                ImageView iv = (ImageView) grid.getChildAt(i);
                iv.setImageResource(pics[i]);

            }


            break;

和xml

中的gridlayout
  <GridLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:rowCount="2"
    android:columnCount="2"
    android:id="@+id/grid">

</GridLayout>

1 个答案:

答案 0 :(得分:0)

我决定使用gridview并且能够完成这项工作。从我之前的阅读开始,我认为网格布局是要走的路。