新建grid_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
</LinearLayout>
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
</LinearLayout>
main.java
package com.example.gallerydemo;
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.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ViewSwitcher.ViewFactory;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class MainActivity extends Activity {
private Gallery myGallery=null;
private SimpleAdapter simpleAdapter=null;
private ImageSwitcher imageswitcher=null;
private List<Map<String,Integer>> list=new ArrayList<Map<String,Integer>>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.myGallery=(Gallery) super.findViewById(R.id.myGallery);
this.initAdapter();
this.myGallery.setAdapter(this.simpleAdapter);
this.myGallery.setOnItemClickListener(new OnItemClickListenerImp());
this.imageswitcher=(ImageSwitcher) super.findViewById(R.id.imageswitcher);
this.imageswitcher.setFactory(new ViewFactoryImp());
}
private void initAdapter(){
//取得全部的属性
Field[] fields=R.drawable.class.getDeclaredFields();
for(int i=0;i<fields.length;i++){
//System.out.println(fields[i]);
if(fields[i].getName().startsWith("ispic_")){
Map<String,Integer> map=new HashMap<String, Integer>();
try {
//必须指定名称是img
map.put("img", fields[i].getInt(R.drawable.class));
} catch (Exception e) {
// TODO: handle exception
}
this.list.add(map);
}
}
//如果使用SimpleAdapter需要自己定义内部的布局文件
this.simpleAdapter=new SimpleAdapter(this,this.list ,
R.layout.grid_layout,
new String[]{"img"},
new int[]{R.id.img});
}
private class OnItemClickListenerImp implements OnItemClickListener{
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Map<String,Integer> map=(Map<String, Integer>) parent.getAdapter().getItem(position);
MainActivity.this.imageswitcher.setImageResource(map.get("img"));
}
}
private class ViewFactoryImp implements ViewFactory{
public View makeView() {
ImageView img=new ImageView(MainActivity.this);
img.setBackgroundColor(0xFFFFFFFF);
img.setScaleType(ImageView.ScaleType.CENTER);
img.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
return img;
}
}
}
本文详细介绍了如何在Android应用中使用LinearLayout布局管理器来创建网格布局和图像切换器,同时通过实例展示了如何实现图像轮播和画廊功能。
509

被折叠的 条评论
为什么被折叠?



