画廊视图(Gallery)的功能和用法
Gallery与Spinner组件有共同的父类:AbsSpinner,表明Gallery和Spinner都是一个列表框。它们之间的区别在于Spinner显示的是一个垂直的列表选择框吗,而Gallery显示的是一个水平的列表选择框。下面以一个例子来说明:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"/>
<Gallery
android:id="@+id/gallery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dip"
android:unselectedAlpha="0.6"
android:spacing="2pt"/>
</LinearLayout>
MainActivity.java
package com.example.testgallary; import android.app.Activity; import android.content.res.TypedArray; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.ImageView; public class MainActivity extends Activity { private int[] imageIds = new int[]{ R.drawable.img1, R.drawable.img2, R.drawable.img3, R.drawable.img4, R.drawable.img5, R.drawable.img6, }; private Gallery gallery; private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gallery = (Gallery) findViewById(R.id.gallery); imageView = (ImageView) findViewById(R.id.imageView); BaseAdapter adapter = new BaseAdapter() { @Override public View getView(int position, View convertView, ViewGroup parent) { // 创建一个ImageView ImageView imageView = new ImageView(MainActivity.this); imageView.setImageResource(imageIds[position]); // 设置ImageView的缩放类型 imageView.setScaleType(ImageView.ScaleType.FIT_XY); // 为imageView设置布局参数 imageView.setLayoutParams(new Gallery.LayoutParams(75, 100)); TypedArray typedArray = obtainStyledAttributes( R.styleable.Gallery); imageView.setBackgroundResource(typedArray.getResourceId( R.styleable.Gallery_android_galleryItemBackground, 0)); return imageView; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public Object getItem(int item) { // TODO Auto-generated method stub return item; } @Override public int getCount() { // TODO Auto-generated method stub return imageIds.length; } }; gallery.setAdapter(adapter); gallery.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { imageView.setImageResource(imageIds[position]); } @Override public void onNothingSelected(AdapterView<?> view) { } }); } }
运行结果:
补充:web前端 , HTML/CSS ,