Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

用 Gallery 控件打造遊戲選關界面

編輯:初階開發

遊戲開發中幾乎都會有選關頁面。要實現得快,用 ListView 就夠了;想要效果更出彩,可以選擇 Gallery 控件——它支持手指拖動、點擊選中,天生適合做橫向的關卡列表。

API Demo 裡對 Gallery 有很詳盡的介紹,如果不打算翻 Demo,這裡有我精簡後的完整代碼。

第一步:在布局中定義 Gallery

<?XML version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://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

Adapter 負責控制 Gallery 的圖片來源等數據操作。

public class ImageAdapter extends BaseAdapter {
    private Context mContext;

    private Integer[] mImageIds = {
        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) {
        mContext = c;
    }

    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(192, 192)); // 設置布局尺寸
        i.setScaleType(ImageView.ScaleType.FIT_XY);           // 設置縮放方式
        return i;
    }
}

第三步:Activity 中調用

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);   // 獲取 Gallery 控件
        g.setAdapter(new ImageAdapter(this));                  // 綁定圖片資源

        g.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View v, int position, long id) {
                // 這裡只是測試,實際項目中可以跳轉到對應關卡的 Activity
                Toast.makeText(TestGallery.this, "" + position, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

把 OnItemClickListener 中的 Toast 替換成跳轉邏輯,一個可用的選關界面就成型了。若想進一步美化,可以給 Adapter 加上選中態的背景切換。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved