<1>简介
要实现这一效果,就必须有一个容器来存放Gallery所要显示的图片。这里使用一个继承自BaseAdapter的派生类来装这些图片。我们需要监听其事件setOnItemClickListener,从而确定当前用户选择了那一张图片并通过Toast显示。
首先,我们需要将显示的图片的索引存放在一个int数组中。然后通过setImageResource方法来设置ImageView要显示的图片资源。最后将每张图片的ImageView显示在屏幕上。
<2>关键步骤
Gallery wasdeprecated in API level 16.
This widget is nolonger supported. Other horizontally scrolling widgets include HorizontalScrollView and ViewPager from the support library.
<3>出现的问题
无
<4>代码及解释
效果图:
GalleryActivity.java:
package com.ui.gallery;
import android.app.Activity;
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;
import com.test.R;
public class GalleryActivity extends Activity{
/**
* @ProjectName: [androidtest]
* @Package: [com.ui.grallery.GralleryActivity.java]
* @ClassName: [GralleryActivity]
* @Description:
* @Author: [gmj]
* @CreateDate: [2013-8-28 下午4:16:05]
* @Version: [v1.0]
*/
int [] imageIDs = {
R.drawable.img1 , R.drawable.img2 , R.drawable.img3 , R.drawable.img4 ,
R.drawable.img5 , R.drawable.img6 , R.drawable.img7
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
Gallery gl = (Gallery)this.findViewById(R.id.gallery1);
BaseAdapter ba = new BaseAdapter()
{
@Override
public int getCount() {
// TODO Auto-generated method stub
return imageIDs.length;
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
ImageView iv = new ImageView(GalleryActivity.this);
iv.setImageResource(imageIDs[arg0]);
iv.setScaleType(ImageView.ScaleType.FIT_XY);
iv.setLayoutParams(new Gallery.LayoutParams(640 , 360));
return iv;
}
};
gl.setAdapter(ba);
gl.setOnItemClickListener(
new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Gallery gl = (Gallery)findViewById(R.id.gallery1);
gl.setSelection(arg2);
Toast.makeText(GalleryActivity.this, "点击了第" + arg2 + "张图片", Toast.LENGTH_SHORT).show();
}
});
}
}