main.xml如下:
<LinearLayout 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" android:orientation="vertical" android:gravity="center_horizontal" > <ImageView android:id="@+id/imageView" android:layout_width="270dip" android:layout_height="350dip" android:layout_marginTop="20dip" android:scaleType="fitXY" android:layout_gravity="center_horizontal" /> <Gallery android:id="@+id/gallery" android:layout_width="fill_parent" android:layout_height="wrap_content" android:spacing="10dip" android:unselectedAlpha="0.6" android:layout_gravity="center_horizontal" android:layout_marginTop="40dip" /> </LinearLayout>
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预览图片.点击其中的某张图片时 * 将该图片在ImageView中显示 * */ public class MainActivity extends Activity { private int imagesID []= null; private Gallery mGallery; private ImageView mImageView; private BaseAdapter mBaseAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); mGallery.setAdapter(mBaseAdapter); //mGallery初始时显示的图片 mGallery.setSelection(imagesID.length/2); 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(); //点击时切换图片 mImageView.setImageResource(imagesID[position]); } }); } 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}; mImageView=(ImageView) findViewById(R.id.imageView); //mImageView初始时显示的图片 mImageView.setImageResource(imagesID[imagesID.length/2]); 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(130, 130)); 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; } }; } }