|
目录结构
第一步:
/GalleryDemo/res/layout/gallery_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
androidrientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_gravity="center">
<!--
android:unselectedAlpha 设置选中的图片的透明度
android:spacing 图片之间的空白大小
-->
<Gallery
android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:spacing="10dip"
android:unselectedAlpha="1" />
</LinearLayout>
复制代码
第二步:
/GalleryDemo/src/com/mygallery/activity/GalleryActivity.java
package com.mygallery.activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
public class GalleryActivity extends Activity {
int[] imgIds = {R.drawable.a, R.drawable.b,
R.drawable.c, R.drawable.d, R.drawable.e};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery_layout);
Gallery gallery = (Gallery) findViewById(R.id.gallery);
BaseAdapter adapter = new GalleryAdpter();
gallery.setAdapter(adapter);
OnItemClickListener listener = new OnItemClickListener() {
/*
* parent 发生点击动作的AdapterView
* view 在AdapterView中被点击的视图(它是由adapter提供的一个视图)
* position 视图在adapter中的位置
* id 被点击元素的行id
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Gallery gallery = (Gallery) findViewById(R.id.gallery);
gallery.setSelection(position);
}
};
gallery.setOnItemClickListener(listener);
}
class GalleryAdpter extends BaseAdapter {
@Override
public int getCount() {
return imgIds.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(GalleryActivity.this);
imageView.setImageResource(imgIds[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
return imageView;
}
}
}
复制代码
第三步:
/GalleryDemo/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mygallery.activity"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".GalleryActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>
复制代码
效果图:
图一: 浏览效果
图二: 选中点击后的效果
GalleryDemo.rar (857.93 KB, 下载次数: 0) |
|