1. 程式人生 > >使用XML和JAVA混合控制UI介面

使用XML和JAVA混合控制UI介面

MainActivity:

package com.example.mcq;

import android.support.v7.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.mipmap.img01,R.mipmap.img02,R.mipmap.img03,R.mipmap.img04,
            R.mipmap.img05,R.mipmap.img06,R.mipmap.img07,R.mipmap.img08,
            R.mipmap.img09,R.mipmap.img10,R.mipmap.img11,R.mipmap.img12
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GridLayout layout=(GridLayout)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);
            ViewGroup.LayoutParams params=new ViewGroup.LayoutParams(116,88);
            img[i].setLayoutParams(params);
            layout.addView(img[i]);
        }
    }
}

layout:

<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layout"
    android:orientation="horizontal"
    android:rowCount="3"
    android:columnCount="4"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.mcq.MainActivity">

</GridLayout>