Gallery的简单功能和用法(画廊视图)
Gallery常用属性
布局文件
一个简单的案例,幻灯片式的预览图片 画廊展示,点击图片则ImageView大图展示
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<ImageView android:id="@+id/imageview"
android:layout_width="320dp"
android:layout_height="320dp"/>
<Gallery
android:id="@+id/gallary"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:unselectedAlpha="0.6"
android:spacing="2pt"/>
</LinearLayout>
代码实现
package com.test.gallery;
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 Gallery gallery;
private ImageView imageview;
int [] imageIds = new int[]{
R.drawable.abc_btn_check_to_on_mtrl_000,
R.drawable.abc_btn_check_to_on_mtrl_015,
R.drawable.abc_btn_radio_to_on_mtrl_000,
R.drawable.abc_btn_radio_to_on_mtrl_015,
R.drawable.abc_btn_rating_star_off_mtrl_alpha,
R.drawable.abc_btn_rating_star_on_mtrl_alpha
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找到控件
gallery = (Gallery)findViewById(R.id.gallary);
imageview = (ImageView)findViewById(R.id.imageview);
//创建BaseAdapter适配器,该对象负责为Gallery提供所显示的列表项
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) {
return position;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public int getCount() {
return imageIds.length;
}
};
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) {
}
});
}
}
android其实已经不再推荐使用Gallery组件了,而是推荐其他的水平滚动组件,如HorizontalScrollView和ViewPager来代替Gallery组件,因此在新版本的android中应该少用Gallery组件