Android——使用GridView制作二维布局界面(行、列分布)



1.GridView的三个关键属性

android:numColumns="auto_fit"       每一行显示多少列
android:horizontalSpacing="10dp"   两列之间的间距
android:verticalSpacing="10dp"        两行之间的间距


activity_main.xml




    
    


item.xml



    

    
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{

    private GridView gridView;
    private List> dataList;
    private int[] icon = {R.drawable.address_book,R.drawable.calendar,R.drawable.camera,R.drawable.clock,
            R.drawable.games_control,R.drawable.messenger,R.drawable.ringtone,R.drawable.settings,
            R.drawable.speech_balloon,R.drawable.weather,R.drawable.world,R.drawable.youtube};

    private String[] iconName = {"通讯录","日历","相机","时钟","游戏","短信","铃声",
            "设置","语音","天气","浏览器","视频"};
    private SimpleAdapter adapter;

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

        gridView = (GridView) findViewById(R.id.gridView);
        //1.准备数据源
        dataList = new ArrayList<>();
        //2.新建适配器(SimpleAdapter)
        adapter = new SimpleAdapter(this,getData(),R.layout.item,new String[]{"image","text"},new int[]{R.id.image,R.id.text});
        //3.GridView加载适配器
        gridView.setAdapter(adapter);
        //4.GridView配置事件监听器(OnItemClickListener)
        gridView.setOnItemClickListener(this);
    }

    private List> getData() {
        for (int i = 0; i < icon.length; i++) {
            Map map = new HashMap<>();
            map.put("image",icon[i]);
            map.put("text",iconName[i]);
            dataList.add(map);
        }
        return dataList;
    }

    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {
        Toast.makeText(this,"我是"+iconName[position],Toast.LENGTH_SHORT).show();
    }
}







你可能感兴趣的:(Android)