package com.example.simpleadaptergalleryproject;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;
public class MainActivity extends Activity {
private Gallery gallery=null;
private List<Map<String,Integer>> list=new ArrayList<Map<String,Integer>>();
private SimpleAdapter simpleAdapter=null;
private ImageSwitcher imageSwitcher=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_main);
this.gallery=(Gallery)super.findViewById(R.id.gallery);//取得资源ID
this.imageSwitcher=(ImageSwitcher)super.findViewById(R.id.imageSwitcher);//取得资源ID
this.imageSwitcher.setFactory(new ViewFactorylmpl());//设置转换工厂
this.initAdapter();//初始化适配器
this.gallery.setAdapter(this.simpleAdapter); //设置图片集
this.gallery.setOnItemClickListener(new OnItemClickListenerlmpl());//设置事件
}
private class ViewFactorylmpl implements ViewFactory{
@Override
public View makeView() {
ImageView image=new ImageView(MainActivity.this);
image.setBackgroundColor(0xFFFFFFFF);
image.setScaleType(ImageView.ScaleType.CENTER);
image.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
return image;
}
}
private class OnItemClickListenerlmpl implements OnItemClickListener{
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
//Toast.makeText(MainActivity.this,"一直都很帅,从未被超越",Toast.LENGTH_LONG).show();
Map<String,Integer> map=(Map<String,Integer>)MainActivity.this.simpleAdapter.getItem(arg2);
MainActivity.this.imageSwitcher.setImageResource(map.get("img"));
}
}
private void initAdapter(){//初始化适配器
Field[] field=R.drawable.class.getDeclaredFields();//取得全部属性
for (int i = 0; i < field.length; i++) {
if(field[i].getName().startsWith("ispic_")){ //找到所有以ispic_命名的图片
Map<String,Integer> map=new HashMap<String,Integer>();
try{
map.put("img", field[i].getInt(R.drawable.class)); //设置图片资源
}catch(Exception e){
}
this.list.add(map); //保存图片资源
}
}
this.simpleAdapter=new SimpleAdapter(MainActivity.this,
MainActivity.this.list,//要包装的数据集合
R.layout.img_data, //要使用的资源模板
new String[]{"img"},//要显示map中的Key
new int[]{R.id.img});//与模板中的组建向匹配
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}