Android组件 网格视图(GridView)

/res/layout/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/myGridView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:numColumns="auto_fit"
        android:columnWidth="60dp"
        android:stretchMode="columnWidth"
        android:gravity="center"/>
</LinearLayout>

Java代码如下:

package com.demo.android.gridview;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class MainActivity extends Activity {
	private GridView myGridView;
    //存放桌面应用程序图标
    private List<ResolveInfo> myAppIcon;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        myGridView=(GridView) findViewById(R.id.myGridView);
        //加载桌面图标
        loadAppIcon();
        myGridView.setAdapter(adapter);
    }
    
    private BaseAdapter adapter=new BaseAdapter() {
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView;
			if(convertView==null){
				imageView=new ImageView(MainActivity.this);
				imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
				imageView.setLayoutParams(new GridView.LayoutParams(50,50));
			}else{
				imageView=(ImageView) convertView;
			}
			ResolveInfo info=myAppIcon.get(position);
			imageView.setImageDrawable(info.activityInfo.loadIcon(getPackageManager()));
			return imageView;
		}
		
		/**
		 * 获取指定位置项目的ID
		 */
		@Override
		public long getItemId(int position) {
			return position;
		}
		
		/**
		 * 获取指定位置的项目
		 */
		@Override
		public Object getItem(int position) {
			return myAppIcon.get(position);
		}
		
		/**
		 * 项目个数
		 */
		@Override
		public int getCount() {
			return myAppIcon.size();
		}
	};
    
    
	
    
    /**
     * 加载桌面图标
     */
    private void loadAppIcon() {
    	//创建Intent
		Intent mainIntent=new Intent(Intent.ACTION_MAIN, null);
		//添加桌面应用程序列表到Intent中
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		myAppIcon=getPackageManager().queryIntentActivities(mainIntent, 0);
	}
}



 

你可能感兴趣的:(Android组件 网格视图(GridView))