在游戲開發中,往往要提供選關的頁面,選擇關卡可以簡單地使用listVIEw,如果想效果好一點,可以選擇 用gallery控件。Gallery控件的使用在api demo裡面有很詳盡的用法介紹,如果不想看api demo,下面有我精簡了的代碼:
程序的效果是可以拖動圖片,單擊選擇。
首先在layout裡面定義gallery控件:
- <?XML version="1.0" encoding="utf-8"?>
- <LinearLayout XMLns:android="http://schemas.android.com/apk/res/android"
- android:orIEntation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextVIEw
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello"
- />
- <Gallery
- android:id="@+id/Gallery01"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content">
- </Gallery>
- </LinearLayout>
復制代碼
再定義Adapter,這個類是用來控制gallery的圖片源等操作的。
- package com.ray.test;
- import android.content.Context;
- import android.view.VIEw;
- import android.view.VIEwGroup;
- import android.widget.BaseAdapter;
- import android.widget.Gallery;
- import android.widget.ImageVIEw;
- public class ImageAdapter extends BaseAdapter {
- private Context mContext; //define Context
- private Integer[] mImageIds = { //picture source
- R.drawable.p1,
- R.drawable.p2,
- R.drawable.p3,
- R.drawable.p4,
- R.drawable.p5,
- R.drawable.p6,
- R.drawable.p7,
- R.drawable.p8,
- };
- public ImageAdapter(Context c) { //define ImageAdapter
- mContext = c;
- }
- //get the picture number
- 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]);//set resource for the imageVIEw
- i.setLayoutParams(new Gallery.LayoutParams(192, 192));//layout
- i.setScaleType(ImageVIEw.ScaleType.FIT_XY);//set scale type
- return i;
- }
- }
復制代碼
最後是Activity調用:
- package com.ray.test;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.VIEw;
- import android.widget.AdapterVIEw;
- import android.widget.Gallery;
- import android.widget.Toast;
- import android.widget.AdapterVIEw.OnItemClickListener;
- public class TestGallery extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentVIEw(R.layout.main);
- Gallery g = (Gallery) findVIEwById(R.id.Gallery01);//get Gallery component
- g.setAdapter(new ImageAdapter(this));//set image resource for gallery
- //add listener
- g.setOnItemClickListener(new OnItemClickListener() {
- public void onItemClick(AdapterView parent, VIEw v, int position, long id) {
- //just a test,u can start a game activity
- Toast.makeText(TestGallery.this, "" + position, Toast.LENGTH_SHORT).show();
- }
- });
- }
- }