Gallery与Spinner组件有共同的父类:AbsSpinner,表明Gallery和Spinner都是一个列表框。区别:Spinner显示的是一个垂直的列表框,而Gallery显示的是一个水平的列表框。
示例java代码:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gallery = (Gallery) findViewById(R.id.gallery);
// 获取显示图片的ImageView对象
imageView = (ImageView) findViewById(R.id.imageView);
// 创建一个BaseAdapter对象,该对象负责提供Gallery所显示的列表项
BaseAdapter adapter = new BaseAdapter()
{
@Override
public int getCount()
{
return imageIds.length;
}
@Override
public Object getItem(int position)
{
return position;
}
@Override
public long getItemId(int position)
{
return position;
}
// 该方法的返回的View就是代表了每个列表项
@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;
}
};
gallery.setAdapter(adapter);
gallery.setOnItemSelectedListener(new OnItemSelectedListener()
{
// 当Gallery选中项发生改变时触发该方法
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id)
{
imageView.setImageResource(imageIds[position]);
}
@Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
}
说明:
<>imageView.setImageResource(imageIds[position]);
功能:Sets a drawable as the content of this ImageView.
参数:resId - the resource identifier of the the drawable
<>imageView.setScaleType(ImageView.ScaleType.FIT_XY);
功能:Controls how the image should be resized or moved to match the sizeof this ImageView.
参数:scaleType - The desired scaling mode.
<>imageView.setLayoutParams(new Gallery.LayoutParams(75, 100));
功能:Set the layout parameters associated with this view. These supplyparameters to the parent of this view specifying how it should bearranged.
There are many subclasses of ViewGroup.LayoutParams, and thesecorrespond to the different subclasses of ViewGroup that are responsiblefor arrangin
g their children.
参数:params - the layout parameters for this view
<><>Gallery.LayoutParams(75, 100)
利用LayoutParams(int w, int h)的构造方法进行初始化。
功能:Gallery extends LayoutParams to provide a place to hold currentTransformation information along with previous position/transformationinfo.
<> obtainStyledAttributes(int[] attrs)
功能:Retrieve styled attribute information in this Context's theme.
<>TypedArray
功能:Container for an array of values that were retrieved obtainStyledAttributes().该类定义容器存储数据。
<>setBackgroundResource(int resid)
功能:Set the background to a given resource. The resource should refer to a Drawable object.
参数:resid - The identifier of the resource.
显示效果: