main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Gallery android:id="@+id/gallery" android:layout_width="wrap_content" android:layout_height="wrap_content" android:spacing="10dip" android:unselectedAlpha="0.6" android:layout_marginTop="30dip" android:layout_centerHorizontal="true" /> </RelativeLayout>
MainActivity如下:
import android.os.Bundle; import android.app.Activity; 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.Toast; import android.widget.AdapterView.OnItemClickListener; /** * Demo描述: * 利用Gallery展示图片 * 问题描述: * 在布局文件中为Gallery设置属性 * android:unselectedAlpha="0.6" * 但在运行时出现bug,其余的图片的透明度 * 亦被设置为0.6. * 解决办法: * 在BaseAdapter中getView()方法处为每个返回的View设置 * 透明背景 * */ public class MainActivity extends Activity { private int imagesID []= null; private Gallery mGallery; private BaseAdapter mBaseAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); mGallery.setAdapter(mBaseAdapter); mGallery.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view,int position, long id) { Toast.makeText(getApplicationContext(), "点击了第" + (position + 1) + "张图片", Toast.LENGTH_SHORT).show(); } }); } private void init() { mGallery=(Gallery) findViewById(R.id.gallery); imagesID=new int []{ R.drawable.a,R.drawable.b,R.drawable.c,R.drawable.d, R.drawable.e,R.drawable.f,R.drawable.g,R.drawable.h}; mBaseAdapter = new BaseAdapter() { @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView = new ImageView(MainActivity.this); //设置图片来源 imageView.setImageResource(imagesID[position]); //拉伸图片以填充View的高宽 imageView.setScaleType(ImageView.ScaleType.FIT_XY); //控制显示图片的大小 imageView.setLayoutParams(new Gallery.LayoutParams(450, 680)); imageView.setBackgroundColor(0xFF000000); return imageView; } @Override public long getItemId(int position) { return position; } @Override public Object getItem(int position) { return position; } @Override public int getCount() { return imagesID.length; } }; } }