完成圖
layout上建立ImageView Gallery
1.建立 attr.xml
2.主程式 MainActivity.java
- package org.galleryEx;
- //匯入類別庫
- import android.app.Activity;
- import android.content.Context;
- import android.content.res.TypedArray;
- import android.os.Bundle;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.AdapterView;
- import android.widget.AdapterView.OnItemClickListener;
- import android.widget.BaseAdapter;
- import android.widget.Gallery;
- import android.widget.ImageView;
- import android.widget.Toast;
- public class MainActivity extends Activity {
- //宣告資料型態
- ImageView imageView;
- Gallery gallery;
- //宣告圖片陣列,檔案必須匯入到圖片資料夾
- private Integer[] images = {
- R.drawable.baby0, R.drawable.baby1, R.drawable.baby2, R.drawable.baby3,
- R.drawable.baby4, R.drawable.baby5, R.drawable.baby6
- };
- //建立Adapter
- public class ImageAdapter extends BaseAdapter {
- int Background;
- private Context context;
- //建構元
- public ImageAdapter(Context c) {
- context = c;
- //獲取陣列
- TypedArray attr = context.obtainStyledAttributes(R.styleable.GalleryCCTU);
- //變更背景
- Background = attr.getResourceId(
- R.styleable.GalleryEx_android_galleryItemBackground, 0);
- //回收記憶體資源
- attr.recycle();
- }
- @Override
- //回傳幾張圖片
- public int getCount() {
- return images.length;
- }
- @Override
- public Object getItem(int position) {
- return position;
- }
- @Override
- public long getItemId(int position) {
- return position;
- }
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- ImageView imageView;
- //如果convertView為空,設定預設值到imageView,不然秀出點選圖
- if (convertView == null) {
- imageView = new ImageView(context);
- imageView.setLayoutParams(new Gallery.LayoutParams(150, 150));
- imageView.setScaleType(ImageView.ScaleType.FIT_XY);
- imageView.setBackgroundResource(Background);
- } else {
- imageView = (ImageView)convertView;
- }
- //獲取點選而改變圖片並回傳
- imageView.setImageResource(images[position]);
- return imageView;
- }
- }
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- findViews();
- }
- private void findViews() {
- imageView = (ImageView)findViewById(R.id.imageView);
- gallery = (Gallery) findViewById(R.id.gallery);
- //設定gallery Adapter
- gallery.setAdapter(new ImageAdapter(this));
- //監聽gallery點擊圖片 即改變圖片到ImageView
- gallery.setOnItemClickListener(new OnItemClickListener() {
- public void onItemClick(AdapterView> parent, View v, int position, long id) {
- //秀出訊息
- Toast.makeText(MainActivity.this, "第 " + position+" 張", Toast.LENGTH_SHORT).show();
- //改變圖片到ImageView
- imageView.setImageResource(images[position]);
- }
- });
- }
- }
復制代碼
|