android学习之Gallery(画廊)

今天看见有同学再问关于画廊那种效果怎么实现,其实自己当时也不知道那叫画廊。嘿嘿。不过还是做了一下。练哈手。

不过看了哈资料,貌似android不再推荐使用这种了 推荐viewPager来实现  在新版本上尽量使用。

先上效果图:

 

代码如下:

public class MainActivity extends Activity {
private  Gallery gallery;
private ImageView imageView;
private Integer[] mImageIds ={
        R.drawable.a,
        R.drawable.b,
        R.drawable.c,
        R.drawable.e,
        R.drawable.f
};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView=(ImageView) findViewById(R.id.imageView);
        imageView.setImageResource(R.drawable.a);
        gallery=(Gallery) findViewById(R.id.gallery);
        //创建一个adapter对象
        BaseAdapter adapter=new BaseAdapter() {
        
            @Override
            public View getView(int imageItem, View convertView, ViewGroup parent) {
                //创建一个ImageView
                ImageView image=new ImageView(MainActivity.this);
                image.setImageResource(mImageIds[imageItem]); //设置图片
                //设置imageView的缩放类型
                image.setScaleType(ImageView.ScaleType.FIT_XY);
                //设置ImageViewde 的布局参数
                image.setLayoutParams(new Gallery.LayoutParams(75, 100));
                return image;
            }    
            @Override
            public long getItemId(int position) {
                return position;
            }
            
            @Override
            public Object getItem(int position) {
                // TODO Auto-generated method stub
                return position;
            }
            
            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return mImageIds.length;
            }
        };
        gallery.setAdapter(adapter);
        gallery.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                        imageView.setImageResource(mImageIds[arg2]);
            }
            
        });
    }
}

Activity代码如下:

<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"
 >
 <ImageView 
     android:id="@+id/imageView"
     android:layout_width="320dp"
     android:layout_height="320dp"
     android:contentDescription="TODO"/>
<Gallery 
    android:id="@+id/gallery"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="bottom|center_vertical"
    android:spacing="2dp"
    android:layout_marginTop="25dp"
    android:unselectedAlpha="0.6"
    />
  
</LinearLayout>

 

 

posted @ 2013-12-03 23:27  小小小小小小菜鸟  阅读(694)  评论(0编辑  收藏  举报