Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1468225
  • 博文数量: 842
  • 博客积分: 12411
  • 博客等级: 上将
  • 技术积分: 5772
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-14 14:43
文章分类

全部博文(842)

文章存档

2013年(157)

2012年(685)

分类: Android平台

2013-03-27 15:06:32

原文地址:Android布局:GridView 作者:tkchks


Layout文件gridview_demo.xml

点击(此处)折叠或打开

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <GridView xmlns:android=""
  3.     android:id="@+id/gridViewDemo"
  4.     android:layout_width="match_parent"
  5.     android:layout_height="match_parent"
  6.     android:numColumns="auto_fit"
  7.     android:gravity="center"
  8.     android:textAlignment="center"
  9.     android:columnWidth="50dp"
  10.     android:stretchMode="columnWidth" >
  11. </GridView>



GridViewActivity类:


点击(此处)折叠或打开

  1. package com.example.twiter;

  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.view.View;
  5. import android.widget.AdapterView;
  6. import android.widget.AdapterView.OnItemClickListener;
  7. import android.widget.ArrayAdapter;
  8. import android.widget.GridView;
  9. import android.widget.TextView;
  10. import android.widget.Toast;

  11. public class GridViewActivity extends Activity {

  12.     GridView gridView;
  13.     
  14.     static final String[] numbers = new String[] {
  15.             "A", "B", "C", "D", "E",
  16.             "F", "G", "H", "I", "J",
  17.             "K", "L", "M", "N", "O",
  18.             "P", "Q", "R", "S", "T",
  19.             "U", "V", "W", "X", "Y", "Z"};
  20.     
  21.     @Override
  22.     protected void onCreate(Bundle savedInstanceState) {
  23.         
  24.         super.onCreate(savedInstanceState);
  25.         setContentView(R.layout.gridview_demo);
  26.         
  27.         gridView = (GridView) findViewById(R.id.gridViewDemo);
  28.         
  29.         ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
  30.                 android.R.layout.simple_list_item_1, numbers);
  31.  
  32.         gridView.setAdapter(adapter);
  33.  
  34.         gridView.setOnItemClickListener(new OnItemClickListener() {
  35.             public void onItemClick(AdapterView<?> parent, View v,
  36.                 int position, long id) {
  37.              Toast.makeText(getApplicationContext(),
  38.                 ((TextView) v).getText(), Toast.LENGTH_SHORT).show();
  39.             }
  40.         });
  41.     }

  42. }


AndroidManifest.xml文件中添加以下行:


点击(此处)折叠或打开

  1. <activity android:name="com.example.twiter.GridViewActivity">
  2.               <intent-filter>
  3.                 <action android:name="android.intent.action.MAIN" />
  4.                 <category android:name="android.intent.category.LAUNCHER" />
  5.             </intent-filter>
  6.          </activity>

效果图:

阅读(1558) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~