首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

实例HelloGallery

2012-09-21 
范例HelloGalleryAndroid docs中的范例,简单翻译整理如下。--------------------------------------------1

范例HelloGallery
Android docs中的范例,简单翻译整理如下。
--------------------------------------------
1、创建新项目,名称HelloGallery;

2、准备一些图片文件,放到res/drawable/目录下;

3、修改res/layout/目录下main.xml,内容如下:

<?xml version="1.0" encoding="utf-8"?><Gallery xmlns:android="http://schemas.android.com/apk/res/android"     android:id="@+id/gallery"    android:layout_width="fill_parent"    android:layout_height="wrap_content"/>


4、在res/values/目录下,新建文件attrs.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="HelloGallery">        <attr name="android:galleryItemBackground" />    </declare-styleable></resources>


5、打开HelloGallery.java,修改后的代码如下:
public class HelloGallery extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);Gallery g = (Gallery) findViewById(R.id.gallery);g.setAdapter(new ImageAdapter(this));g.setOnItemClickListener(new OnItemClickListener() {public void onItemClick(AdapterView<?> parent, View v, int position, long id) {Toast.makeText(HelloGallery.this, "" + position, Toast.LENGTH_SHORT).show();}});}public class ImageAdapter extends BaseAdapter {int mGalleryItemBackground;private Context mContext;// 图片资源的名称需要根据准备的图片名称进行修改private Integer[] mImageIds = {R.drawable.expo01, R.drawable.expo02, R.drawable.expo03, R.drawable.expo04, R.drawable.expo05,R.drawable.expo06, R.drawable.expo07, R.drawable.expo08};public ImageAdapter(Context c) {mContext = c;TypedArray a = obtainStyledAttributes(R.styleable.HelloGallery);mGalleryItemBackground = a.getResourceId(R.styleable.HelloGallery_android_galleryItemBackground, 0);a.recycle();}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(150, 100));i.setScaleType(ImageView.ScaleType.FIT_XY);i.setBackgroundResource(mGalleryItemBackground);return i;}}}


6、运行项目,即可看到运行效果,如下图所示:

热点排行