閱讀989 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Gallery


Gallery.java

public class xiangbu extends Activity 
{
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) 
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    /*通過findViewById取得*/
    Gallery g = (Gallery) findViewById(R.id.mygallery);
    /* 添加一ImageAdapter並設置給Gallery對象 */
    g.setAdapter(new ImageAdapter(this));
    
    /* 設置一個itemclickListener並Toast被點擊圖片的位置 */
    g.setOnItemClickListener(new OnItemClickListener() 
    {
      public void onItemClick
      (AdapterView<?> parent, View v, int position, long id)
      {
        Toast.makeText
        (xiangbu.this, getString(R.string.my_gallery_text_pre)
        + position+ getString(R.string.my_gallery_text_post), 
        Toast.LENGTH_SHORT).show();
      }
    });
  }
  
  /* 改寫BaseAdapter自定義一ImageAdapter class */
  public class ImageAdapter extends BaseAdapter 
  {
    /*聲明變量*/
    int mGalleryItemBackground;
    private Context mContext;
    
    /*ImageAdapter的構造器*/
    public ImageAdapter(Context c) 
    {
      mContext = c;
      
      /* 使用在res/values/attrs.xml中的<declare-styleable>定義
      * 的Gallery屬性.*/
      TypedArray a = obtainStyledAttributes(R.styleable.Gallery);
      
      /*取得Gallery屬性的Index id*/
      mGalleryItemBackground = a.getResourceId
      (R.styleable.Gallery_android_galleryItemBackground, 0);
      
      /*讓對象的styleable屬性能夠反複使用*/ 
      a.recycle();
    }
    
    /* 覆蓋的方法getCount,返回圖片數目 */
    public int getCount() 
    {
      return myImageIds.length;
    }
         
    /* 覆蓋的方法getItemId,返回圖像的數組id */

    public Object getItem(int position) 
    {
      return position;
    }
    public long getItemId(int position) 
    {
      return position;
    }
    
    /* 覆蓋的方法getView,返回一View對象 */
    public View getView
    (int position, View convertView, ViewGroup parent)
    {
      /*產生ImageView對象*/
      ImageView i = new ImageView(mContext);
      /*設置圖片給imageView對象*/
      i.setImageResource(myImageIds[position]);
      /*重新設置圖片的寬高*/
      i.setScaleType(ImageView.ScaleType.FIT_XY);
      /*重新設置Layout的寬高*/
      i.setLayoutParams(new Gallery.LayoutParams(136, 88));
      /*設置Gallery背景圖*/
      i.setBackgroundResource(mGalleryItemBackground);
      /*返回imageView對象*/
      return i;
    }
    
    /*建構一Integer array並取得預加載Drawable的圖片id*/
    private Integer[] myImageIds = 
    {
      R.drawable.photo1,
      R.drawable.photo2,
      R.drawable.photo3,
      R.drawable.photo4,
      R.drawable.photo5,
      R.drawable.photo6,
    };   
  } 
}

main.xml

<Gallery xmlns:andro 
  android:
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
/>










最後更新:2017-04-02 16:48:16

  上一篇:go 開源項目(不斷收集中....)
  下一篇:go PicoContainer(Ioc容器)在測試用例中的應用(二)