5.2 Android Basic QuickStart Widgets&Other View Gallery

Gallery

Gallery是一个水平滚动项的布局控件。

本演练将创建一个相册走廊,同时显示选中的图片信息。

   

  • 新建项目HelloGallery。
  • 将使用的图片放入res/drawable目录。

       

    3. 打开res/layout/main.xml文件编辑如下。

    <?xml version="1.0" encoding="utf-8"?>

    <FrameLayout android:id="@+id/FrameLayout01"

    android:layout_width="fill_parent" android:layout_height="fill_parent"

    xmlns:android="http://schemas.android.com/apk/res/android">

    <Gallery android:background="#55000000"

    android:id="@+id/gallery"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:gravity="center_vertical"

    android:spacing="16dp"/>

    </FrameLayout>

    4. 打开HelloGallery.java 修改onCreate()方法。

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    Gallery g = (Gallery)findViewById(R.id.gallery);

    g.setAdapter(new ImageAdapter(this));

    g.setOnItemClickListener(new OnItemClickListener(){

       

    @Override

    public void onItemClick(AdapterView<?> arg0, View arg1, int position,

    long id) {

    Toast.makeText(HelloGallery.this, ""+position, Toast.LENGTH_SHORT).show();

    }

    });

    }

    5. 在res/values下创建attrs.xml文件,编辑内容如下。

    <?xml version="1.0" encoding="UTF-8"?>

    <resources>

    <declare-styleable name="HelloGallery">

    <attr name="android:galleryItemBackground"/>

    </declare-styleable>

    </resources>

    6. 返回hellogallery.java 自定义ImageAdapter类。

    public class ImageAdapter extends BaseAdapter {

    int mGalleryItemBackground;

    private Context mContext;

    private Integer[] mImageIds = { R.drawable.sample_1,

    R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4,

    R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7 };

       

    public ImageAdapter(Context c) {

    mContext = c;

    TypedArray a = obtainStyledAttributes(R.styleable.HelloGallery);

    mGalleryItemBackground = a.getResourceId(

    R.styleable.HelloGallery_android_galleryItemBackground, 0);

    a.recycle();

    }

       

    public int getCount() {

    return mImageIds.length;

    }

       

    public Object getItem(int position) {

    return position;

    }

       

    public long getItemId(int position) {

    return position;

    }

       

    public View getView(int position, View convertView, ViewGroup parent) {

    ImageView i = new ImageView(mContext);

    i.setImageResource(mImageIds[position]);

    i.setLayoutParams(new Gallery.LayoutParams(150, 100));

    i.setScaleType(ImageView.ScaleType.FIT_XY);

    i.setBackgroundResource(mGalleryItemBackground);

    return i;

    }

    }

    7. 运行程序。

       

    author: im@xingquan.org

posted @ 2011-03-25 16:29  敏捷学院  阅读(284)  评论(0编辑  收藏  举报