画廊控件(Gallery)

1、首先给大家展示一个示例:(看一下Java代码)

public class AActivity extends Activity {
 ImageSwitcher imgSwt;
 Gallery glr;
 //需要显示的图片资源,保存在drawable目录下
 int[] imgs={
   R.drawable.a,R.drawable.b,R.drawable.c,R.drawable.d,R.drawable.e,R.drawable.f,R.drawable.g
 };
 //缓存底部在Gallery中使用的ImageView
 ImageView[] galleryViews=new ImageView[imgs.length];
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_a);
        imgSwt=(ImageSwitcher)findViewById(R.id.imgSwt);
        glr=(Gallery)findViewById(R.id.glr);
        //设置ImageSwitcher显示图片的工厂
        imgSwt.setFactory((new ViewFactory()
  {
   @Override
   public View makeView()
   {
   ImageView iv=new ImageView(AActivity.this);
   iv.setBackgroundColor(0xFF000000);
   iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
   iv.setLayoutParams(new ImageSwitcher.LayoutParams(
     LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
    return iv;
   }
  }));
        //设置ImageSwitcher的进入动画
        imgSwt.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in));
        //设置ImageSwitcher的退出动画
        imgSwt.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_out));
        //初始化缓存Gallery使用的ImageView
        for (int i = 0; i < galleryViews.length; i++)
  {
   ImageView iv=new ImageView(AActivity.this);
   iv.setImageResource(imgs[i]);
   iv.setAdjustViewBounds(true);
   iv.setLayoutParams(new Gallery.LayoutParams(
   LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
   galleryViews[i]=iv;
  }
        //设置Gallery的适配器
        glr.setAdapter(new BaseAdapter(){
   @Override
   public int getCount(){
    return imgs.length;
   }
   @Override
   public Object getItem(int position){
    return null;
   }
   @Override
   public long getItemId(int position)
   {
    // TODO Auto-generated method stub
    return 0;
   }
   @Override
   public View getView(int position, View convertView, ViewGroup parent)
   {
    // TODO Auto-generated method stub
    return galleryViews[position];
   }
  });
        //Gallery被选中的事件
        glr.setOnItemSelectedListener(new OnItemSelectedListener()
  {
         @Override
         public void onItemSelected(AdapterView arg0,View arg1,int arg2,long arg3)
         {
          imgSwt.setImageResource(imgs[arg2]);
         }
         @Override
         public void onNothingSelected(AdapterView arg0){
          //
         }
  });
    }

}

 

2、它的XML 布局文件:

 

    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

            android:id="@+id/imgSwt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
                android:id="@+id/glr"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

 

3、其显示出来的效果图:

上面运用了tabhost组件,下面用是一个画廊空间