main.xml
先定义一个GridView,然后再定义一个ImageSwitcher
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" > <GridView android:id="@+id/gridView1" android:layout_height="fill_parent" android:layout_width="300px" android:layout_marginTop="6px" android:horizontalSpacing="3px" android:verticalSpacing="3px" android:numColumns="4"/> <ImageSwitcher android:id="@+id/imageSwicher1" android:padding="20px" android:layout_width="fill_parent" android:layout_height="fill_parent" ></ImageSwitcher> </LinearLayout>
MainActivity代码如下:
public class MainActivity extends Activity { private int[] imageId = new int[] { R.drawable.w1, R.drawable.w2, R.drawable.w3, R.drawable.w4, R.drawable.w5, R.drawable.w6 }; private ImageSwitcher imageSwitcher; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.main); imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwicher1); imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));// 设置淡入动画 imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));// 设置谈出动画 imageSwitcher.setFactory(new ViewFactory() { @Override public View makeView() { // TODO Auto-generated method stub ImageView imageView = new ImageView(MainActivity.this);// 实例化一个ImageView类的对象 imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);// 设置保持纵横比居中缩放图像 imageView.setLayoutParams(new ImageSwitcher.LayoutParams(// 主要要是用ImageSwitcher的LayoutParams LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); return imageView; } }); imageSwitcher.setImageResource(imageId[0]); GridView gridView = (GridView) findViewById(R.id.gridView1); BaseAdapter adapter = new BaseAdapter() { /* * 获得数量 * * @see android.widget.Adapter#getCount() */ @Override public int getCount() { // TODO Auto-generated method stub return imageId.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } /** * 获得当前选项 */ @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ImageView imageView; if (convertView == null) { imageView = new ImageView(MainActivity.this); /** 设置图像的宽度和高度 **/ imageView.setAdjustViewBounds(true); imageView.setMaxWidth(150); imageView.setMaxHeight(113); imageView.setPadding(5, 5, 5, 5); } else { imageView = (ImageView) convertView; } imageView.setImageResource(imageId[position]); return imageView; } }; gridView.setAdapter(adapter); gridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub imageSwitcher.setImageResource(imageId[arg2]);// 显示选中的图片 } }); } }
效果图: