Android应用中使用GridView实现数据网格显示(传智播客视频笔记)

Android应用中使用GridView实现数据网格显示

UsingGridView.java源码:

package com.sinaapp.ssun.girdview;

import java.util.*;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class UsingGridViewActivity extends Activity {
	private GridView gridView;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);         
       
        gridView = (GridView) this.findViewById(R.id.gridView);        
        show();
    } 

	private void show() {  
		List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
		for(int i=0; i<12; i++){
			HashMap<String, Object> hm = new HashMap<String, Object>();
			hm.put("image", R.drawable.ic_launcher);
			hm.put("name", "NO." + i);
			data.add(hm);
		}
		
		SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item, 
                                        new String[]{"image","name"},new int[]{R.id.imageView,R.id.textView});
		
 		gridView.setAdapter(adapter);
 		
 		gridView.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				HashMap<String, Object> hm = (HashMap<String, Object>)parent.getItemAtPosition(position);
				Toast.makeText(UsingGridViewActivity.this, hm.get("name").toString(), Toast.LENGTH_LONG).show();
			}});
	}
}

main.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <GridView
        android:id="@+id/gridView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:numColumns="3" >
    </GridView>
    
</LinearLayout>

item.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" 
        android:layout_gravity="center_horizontal"/>

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>
    
</LinearLayout>

本文章是在参考http://blog.csdn.net/hellogv/article/details/4567095写的,如果没有那篇文章,可能今天晚上又没得睡了,谢谢他了。



你可能感兴趣的:(Android应用中使用GridView实现数据网格显示(传智播客视频笔记))