在游戏开发中,往往要提供选关的页面,选择关卡可以简单地使用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();
- }
- });
- }
- }