Android Activity-GridView使用学习

jopen 13年前
     <p>我们将通过两个例子学习GridView。Grid和Table有一点点类似。我们将在例子中逐步描绘如何编写一个Grid的Activity</p>    <p><big><strong>例子一:继承ArrayAdapter作为自定义adapter</strong></big></p>    <p>1、编写Android XML</p>    <blockquote style="border-bottom:#ffbcbc thin dashed;border-left:#ffbcbc thin dashed;padding-bottom:5pt;line-height:130%;background-color:#ffffea;margin-top:11px;text-indent:0em;padding-left:5pt;padding-right:5pt;font-family:微软雅黑;margin-bottom:11px;margin-left:10pt;font-size:9.5pt;border-top:#ffbcbc thin dashed;border-right:#ffbcbc thin dashed;padding-top:5pt;">     <p><span style="color:#888888;"><?xml version="1.0" encoding="utf-8"?><br /> <LinearLayout<br />   xmlns:android="http://schemas.android.com/apk/res/android"<br />   android:orientation="vertical"<br />   android:layout_width="fill_parent"<br />   android:layout_height="fill_parent"><br />   <TextView android:id="@+id/selection4"<br />     android:layout_width="fill_parent"<br />     android:layout_height="wrap_content" /></span><br />   <<strong>GridView</strong> <span style="color:#888888;">android:id="@+id/grid"<br />     android:layout_width="fill_parent"<br />     android:layout_height="fill_parent"</span><br />     android:<strong>verticalSpacing</strong>="35px" <span style="color:#6666ff;"><!-- grid元素之间的竖直间隔 --></span><br />     android:<strong>horizontalSpacing</strong>="5px"  <span style="color:#6666ff;"><!--</span><span style="color:#6666ff;">grid元素之间的水平间隔 </span><span style="color:#6666ff;"> --></span><br />     android:<strong>numColumns</strong>="auto_fit" <span style="color:#6666ff;"><!--表示有多少列,如果设置为auto_fit,将根据columnWidth和Spacing来自动计算 --></span><br />     android:<strong>columnWidth</strong>="100px" <span style="color:#6666ff;"><!-- 一般建议采用有像素密度无关的dip或者dp来表示--></span><br />     android:<strong>stretchMode</strong>="columnWidth" <span style="color:#6666ff;"><!--如何填满空余的位置,模拟器采用WVGA800*480,每排4列,有4*100+5*3=415,还余65px的空间,如果是 columnWidth,则这剩余的65将分摊给4列,每列增加16/17px。如果采用SpacingWidth,则分摊给3个间隔空隙 --></span><br />     android:gravity="center"  />  <br /> <span style="color:#888888;"></LinearLayout></span></p>    </blockquote>    <p>2、编写代码。和其他selected widget,我们之前学习的ListView和Spinner的方式,通过setAdapter()来提供数据和子View显示风格,通过触发 setOnItemSelectedListener()注册选择listner。在这里处理选择之外,我们增加一个Click的触发,可以比较一下此两 的差异。此次我们不再使用Android自带的格式,而设置我们自己的UI风格。</p>    <blockquote style="border-bottom:#ffbcbc thin dashed;border-left:#ffbcbc thin dashed;padding-bottom:5pt;line-height:130%;background-color:#ffffea;margin-top:11px;text-indent:0em;padding-left:5pt;padding-right:5pt;font-family:微软雅黑;margin-bottom:11px;margin-left:10pt;font-size:9.5pt;border-top:#ffbcbc thin dashed;border-right:#ffbcbc thin dashed;padding-top:5pt;">     <p>public class Chapter7Test4 extends Activity  implements  <strong>OnItemSelectedListener</strong>,<strong>OnItemClickListener</strong>{<br /> <span style="color:#888888;">    private TextView selection = null;<br />     private String[] items={"lorem", "ipsum", "dolor", "sit", "amet", "hello", "me", "elit", "morbi", "vel", "ligula", "vitae", "arcu", "aliquet", "mollis", "etiam", "vel", "erat", "placerat", "ante","hi", "sodales", "test", "augue", "purus"};</span><br /> <span style="color:#888888;"><br />     @Override</span><br />     protected void onCreate(Bundle savedInstanceState) {<br /> <span style="color:#888888;">        super.onCreate(savedInstanceState);<br />         setContentView(R.layout.chapter_7_test4);<br />         </span><br /> <span style="color:#888888;">        selection = (TextView)findViewById(R.id.selection4);</span><br />         GridView grid= (GridView)findViewById(R.id.grid);<br />         <span style="color:#003366;">/<strong>/步骤1:设置ArrayAdapter,可以采用android自带的格式,也可以自定义,这里我们将自己定义。</strong></span><br />         grid.<strong>setAdapter</strong>( new <em><strong>FunnyLookingAdapter</strong></em>(this, android.R.layout.simple_list_item_1,items));<br />         <span style="color:#888888;">//grid.setAdapter(new ArrayAdapter       <string>        (this,android.R.layout.simple_list_item_1,items));       </string></span><br />        <span style="color:#003366;"><strong> //步骤2:设置元素被选择以及被点击的回调触发处理</strong></span><br />         grid.<strong>setOnItemSelectedListener</strong>(this);<br />         grid.<strong>setOnItemClickListener</strong>(this);<br />     }<br /> <span style="color:#003366;"><strong>  //步骤3:编写CallBack触发函数</strong></span><br />    <span style="color:#808080;"> @Override</span><span style="color:#008000;"> /* 这是OnItemSelectedListener接口*/</span><br />     public void onItemSelected(AdapterView      <!--?--> arg0, View arg1, int arg2, long arg3) {<br />         selection.setText(items[arg2]);<br />     }<br /> <br /> <span style="color:#808080;">    @Override</span> <span style="color:#008000;">/* 这是OnItemSelectedListener接口*/</span><br />     public void onNothingSelected(AdapterView      <!--?--> arg0) {<br />         selection.setText("");<br />     }<br /> <br /> <span style="color:#808080;">    @Override</span> <span style="color:#008000;">/* 这是OnItemClickListener接口*/</span><br />     public void onItemClick(AdapterView      <!--?--> arg0, View arg1, int arg2, long arg3) {<br />         selection.setText("Clicked: " + items[arg2]);<br />     }<br /> <br />    <span style="color:#003366;"><strong>//步骤4:编写自定义的adapter,继承ArrayAdapter        <string></string></strong></span><br />     private class <strong>FunnyLookingAdapter extends ArrayAdapter       <string></string></strong>{<br /> <span style="color:#808080;">        private Context context;<br />         private String[] theItems;</span><br />         <span style="color:#003366;"><strong>//步骤4.1:编写adapter</strong></span><strong><span style="color:#003366;">的构造函数</span></strong><br />         FunnyLookingAdapter( Context context, int resource, String[] items){<br />                 <strong>super(context,resource,items);</strong><br />                 this.context = context;<br />                 theItems = items;<br />         }<br />         <br />         <span style="color:#003366;"><strong>//步骤4.2:</strong></span><span style="color:#003366;"><strong>重写getView(),</strong></span><span style="color:#003366;"><strong>对每个单元的内容以及UI格式进行描述</strong></span><br />         <span style="color:#008000;">/*如果我们不使用TextView,则我们必须通过getView()对每一个gridview单元进行描述。这些单元可以是Button,ImageView,在这里我们使用Button和TextView分别作测试 重<span style="color:#008000;">写</span></span><span style="color:#008000;">override getView(int, View, ViewGroup),返回任何我们所希望的view。</span><span style="color:#008000;">*/</span><br />         public View   <strong>getView</strong>  (int position, View  convertView, ViewGroup  parent){<br />             TextView label = (TextView)convertView;<br /> <span style="color:#008000;">            //我们测试发现,除第一个convertView外,其余的都是NULL,因此如果没有view,我们需要创建</span><br />             if(convertView == null){<br />                 convertView = new TextView(context);<br />                 label = (TextView)convertView;<br />             }<br />             <br />             label.setText(position + ": "  + theItems[position]);            <br />             return convertView;<br />         }<br />     }<span style="color:#808080;">// End of class FunnyLookingAdapter</span><br /> <br /> }</p>    </blockquote>    <p><img style="width:702px;height:366px;" alt="Android Activity-GridView使用学习" src="https://simg.open-open.com/show/c8dbf5f32b26fc9aa6703d0f0e3ce2c5.png" /> </p>    <p>左图是使用android自带的粗体格式,即被注释掉的setAdapter,图二为例子源代码示例,图右将 FunnyLookingAdapter中的getView()用Button代替TextView,这是发现有一个有趣的现象,Button是检测 Click动作,而我们在类中通过setItemClickListener中设置了对GridView中的item检测Click的动作,这两个是重叠 的,而将优先监听Button的Click,即我们定制的GridView中将得不到触发,这需特别注意。</p>    <p><big><strong>例子二:</strong></big><span style="font-family:微软雅黑;"><big><strong>继承BaseAdapter作为自定义adapter</strong></big></span></p>    <p>这是来自Totorial的例子。在这里GridView里面的元素是ImageView。Android XML的文件很简单:</p>    <blockquote style="border-bottom:#ffbcbc thin dashed;border-left:#ffbcbc thin dashed;padding-bottom:5pt;line-height:130%;background-color:#ffffea;margin-top:11px;text-indent:0em;padding-left:5pt;padding-right:5pt;font-family:微软雅黑;margin-bottom:11px;margin-left:10pt;font-size:9.5pt;border-top:#ffbcbc thin dashed;border-right:#ffbcbc thin dashed;padding-top:5pt;">     <p><span style="color:#808080;">       <!--?xml version="1.0" encoding="utf-8"?--></span><br /> <span style="color:#3366ff;">       <!-- dp等同于dip,device independent pixels设备独立像素,多用于android,与分别率无关, --></span><br /> <<strong>GridView </strong><span style="color:#808080;">xmlns:android="http://schemas.android.com/apk/res/android"</span><br /> <span style="color:#808080;">  android:id="@+id/gridview"<br />   android:layout_width="fill_parent"<br />   android:layout_height="fill_parent"</span><br />   android:<strong>columnWidth</strong>="90dp"<br />   android:<strong>numColumns</strong>=<em><strong>"auto_fit"</strong></em><br />   android:<strong>verticalSpacing</strong>="10dp"<br />   android:<strong>horizontalSpacing</strong>="10dp"<br />   android:<strong>stretchMode</strong>=<em><strong>"columnWidth"</strong></em><br />   android:gravity="center" ><br /> </p>    </blockquote>    <p>我们在来看看Java code。</p>    <p>1)我们将<a href="/misc/goto?guid=4959517965761493516">图片</a>,copy至res/drawable-hdpi/中。</p>    <p>2)设置GridView的adapter,并设置点击触发函数,点击后采用Toast显示点击的序号。</p>    <blockquote style="border-bottom:#ffbcbc thin dashed;border-left:#ffbcbc thin dashed;padding-bottom:5pt;line-height:130%;background-color:#ffffea;margin-top:11px;text-indent:0em;padding-left:5pt;padding-right:5pt;font-family:微软雅黑;margin-bottom:11px;margin-left:10pt;font-size:9.5pt;border-top:#ffbcbc thin dashed;border-right:#ffbcbc thin dashed;padding-top:5pt;">     <p>    protected void onCreate(Bundle savedInstanceState) {<br /> <span style="color:#808080;">        super.onCreate(savedInstanceState);<br />         setContentView(R.layout.chapter_7_test5);</span><br />         <br /> <span style="color:#808080;">        GridView gridview = (GridView)findViewById(R.id.gridview);</span><br />         gridview.<strong>setAdapter</strong>(new ImageAdapter(this));<br />         <br />         gridview.<strong>setOnItemClickListener</strong>(new OnItemClickListener(){<br />             public void onItemClick(AdapterView      <!--?--> parent, View v, int position, long id){<br />                 <strong>Toast</strong>.makeText(this, ""+position, Toast.LENGTH_SHORT).show();<br />             }    <br />         });<br />     }</p>    </blockquote>    <p>3)设置我们自子的ImageAdapter,继承BasAdapter。</p>    <blockquote style="border-bottom:#ffbcbc thin dashed;border-left:#ffbcbc thin dashed;padding-bottom:5pt;line-height:130%;background-color:#ffffea;margin-top:11px;text-indent:0em;padding-left:5pt;padding-right:5pt;font-family:微软雅黑;margin-bottom:11px;margin-left:10pt;font-size:9.5pt;border-top:#ffbcbc thin dashed;border-right:#ffbcbc thin dashed;padding-top:5pt;">     <p>    public class <strong>ImageAdapter extends BaseAdapter</strong>{<br /> <span style="color:#808080;">        private Context context = null;</span><br />         // references to our images<br />         private Integer[] mThumbIds = {R.drawable.sample_2, R.drawable.sample_3,R.drawable.sample_4, R.drawable.sample_5,R.drawable.sample_6,<span style="color:#0000ff;">...</span><span style="color:#0000ff;">// 这里是文件的对应的Id,不在具体列出</span>};<br />    <span style="color:#0000ff;">     //步骤1: 构造函数       </span><br />         public ImageAdapter(Context context){<br />             this.context = context;<br />         }<br /> <span style="color:#0000ff;">        //步骤2:</span><span style="color:#0000ff;">BaseAdapter需要重构四个方法</span><span style="color:#0000ff;">getCount(),getItem(),getItemId(int position),getView()</span><br />         <span style="color:#0000ff;">//</span><span style="color:#0000ff;">步骤2.1:getCount() 表示How many items are in the data set represented by this Adapter.</span><br />         public int getCount() {<br />             return mThumbIds.length;<br />         }<br /> <span style="color:#0000ff;">        //步骤2.2:</span><span style="color:#0000ff;">getItem()</span><span style="color:#0000ff;">根据需要position获得布放在GridView的对象。在这个例子中,我们不需要处理里面的对象,可以设为null</span><br />         public Object getItem(int position) {<br />             return null;<br />         }<br />         <span style="color:#0000ff;">//步骤2.3:</span><span style="color:#0000ff;">getItemId()</span><span style="color:#0000ff;">获得row id(</span><span style="color:#0000ff;">Get the row id associated with the specified position in the list)</span><span style="color:#0000ff;">,由于我们也不需要,简单的设为0</span><br />         public long getItemId(int position) {<br />             return 0;<br />         }<br />     <span style="color:#0000ff;">    //</span><span style="color:#0000ff;">步骤2.4:</span><span style="color:#0000ff;">获得GridView里面的View</span>,<span style="color:#0000ff;">Get a View that displays the data at the specified position in the data set.</span> <span style="color:#3366ff;">和第一个例子一样,传递的第二个函数可能为null,必须进行处理。</span><br />         <strong>public View getView(int </strong><em>position</em><strong>, View </strong><em>convertView</em><strong>, ViewGroup </strong><em>parent</em><strong>)</strong> {<br />             ImageView imageView = null;<br />             if(convertView == null){<br />                 imageView = new ImageView(context);<br />                <span style="color:#008080;"> // 设置View的height和width:这样保证无论image原来的尺寸,每个图像将重新适合这个指定的尺寸。</span><br />                 imageView.<strong>setLayoutParams</strong>(new GridView.LayoutParams(85,85));<br /> <span style="color:#008080;">                /* ImageView.ScaleType.CENTER 但不执行缩放比例<br />                  * ImageView.ScaleType.CENTER_CROP 按比例统一缩放图片(保持图片的尺寸比例)便于图片的两维(宽度和高度)等于或大于相应的视图维度<br />                  * ImageView.ScaleType.CENTER_INSIDE 按比例统一缩放图片(保持图片的尺寸比例)便于图片的两维(宽度和高度)等于或小于相应的视图维度 */</span><br />                 imageView.<strong>setScaleType</strong>(ImageView.ScaleType.CENTER_CROP);<br />                 imageView.setPadding(8,8,8,8);<br />             }else{<br />                 imageView = (ImageView)convertView;<br />             }<br />             imageView.<strong>setImageResource</strong>(mThumbIds[position]);<br />             return imageView;<br />         }<br />         <br />     }</p>    </blockquote>    <p>我们设置了几种scaleType,下面左图是ImageView.ScaleType.CENTER_CROP,中图是ImageView.ScaleType.CENTER_INSIDE,右图是ImageView.ScaleType.CENTER</p>    <p><img alt="Android Activity-GridView使用学习" src="https://simg.open-open.com/show/e4aef3c4ed431ea06332ea465b39c5df.png" width="465" height="383" /></p>