android 画廊控件Gallery的使用

来源:互联网 发布:jdk 7u55 linux x64 编辑:程序博客网 时间:2024/05/17 22:18

效果图

 

android <wbr>画廊控件Gallery的使用

 

 


准备八张图
布局文件
<<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical" >>

   <<Gallery
       android:id="@+id/gallery"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_marginTop="30dp" />>

<</LinearLayout>>

在res/values下新建attrs.xml,用来设置画廊控件的背景
<<?xml version="1.0" encoding="utf-8"?>>
<<resources>
   
       ><</attr>>
 <</declare-styleable>>
<</resources>>

 


代码
package com.example.gallery;

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.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class MainActivity extends Activity {

 private Gallery gallery;
 private int[] resIds = { R.drawable.one,R.drawable.two, R.drawable.three,
   R.drawable.four,R.drawable.five, R.drawable.six, R.drawable.seven,
   R.drawable.eight};

 @Override
 protected void onCreate(BundlesavedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  gallery = (Gallery)findViewById(R.id.gallery);
  ImageAdapter adapter = newImageAdapter(this);
  gallery.setAdapter(adapter);
 }

 public class ImageAdapter extends BaseAdapter{
  private Context context;
  int mGalleryItemBackground;//使用一個简单的计数器,填充背景图

  public ImageAdapter(Contextcontext) {
   this.context= context;
   TypedArrayarray = obtainStyledAttributes(R.styleable.Gally);
   //用来填充画廊控件的背景
   mGalleryItemBackground= array.getResourceId(
     R.styleable.Gally_android_galleryItemBackground,0);

  }

  @Override
  public int getCount() {
   returnInteger.MAX_VALUE;
  }

  @Override
  public Object getItem(intposition) {
   returnresIds[position];
  }

  @Override
  public long getItemId(intposition) {
   returnposition;
  }

  @Override
  public View getView(intposition, View convertView, ViewGroup parent) {
   ImageView iv= new ImageView(context);
   iv.setImageResource(resIds[position% resIds.length]);
   iv.setScaleType(ScaleType.FIT_XY);
   iv.setLayoutParams(newGallery.LayoutParams(530, 480));
   iv.setBackgroundResource(mGalleryItemBackground);
   returniv;
  }
 }
}


 


 

0 0
原创粉丝点击