package com.gusfree.listview;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class ImageListActivity extends Activity {
	ListView listView;
	int[] datas={R.drawable.a,R.drawable.b,R.drawable.c,R.drawable.d};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.listview);//inflate
		listView=(ListView)findViewById(R.id.listView1);
		
		ArrayList arrayList =new ArrayList();
		
		/*HashMap오류
		 * HashMap<String,Integer> hashMap =new HashMap<String,Integer>();
		hashMap.put("image",R.drawable.a);//중복불가능
		arraylist.add(hashMap);
		hashMap.put("image",R.drawable.b);
		arraylist.add(hashMap);
		hashMap.put("image",R.drawable.c);
		arraylist.add(hashMap);
		hashMap.put("image",R.drawable.d);
		arraylist.add(hashMap); //결과가 예상과 다르게 나온다. 아래for문 으로
        */		
		for(int i=0;i<datas.length;i++){
			HashMap<String,Integer> hashMap =new HashMap<String,Integer>();
			hashMap.put("image",datas[i]);//중복불가능
			arrayList.add(hashMap);
			}
		
		/* SimpleAdapter*/
		SimpleAdapter adapter = new SimpleAdapter(this,arrayList,R.layout.item,
				new String[]{"image"},//arrayList 안의 맵의 키
				new int[]{R.id.imageView1});//R.layout.item.안의 imageView의 id
		
		listView.setAdapter(adapter);
		
		//MyAdapter adapter=new MyAdapter();
		//listView.setAdapter(adapter);
		
	}
	//inner class
	class MyAdapter extends BaseAdapter{

		@Override
		public int getCount() {//데이터가 몇개냐?
			return datas.length;//4개다
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}
		
		//getCount()리턴 값만큼 실행됩니다.
		//posistion 0,1,2,3
		@Override 
		public View getView(int position, View arg1, ViewGroup arg2) {
			//1.배열에서 이미지 주소를 하나씩 빼오기
			int imageRes = datas[position];
			
			//2.xml 불러오기
			LinearLayout layout=
			(LinearLayout)View.inflate(ImageListActivity.this, R.layout.item, null);
			
			//3.xml안의 ImageView 찾기
			ImageView imageView =(ImageView)layout.findViewById(R.id.imageView1);
			
			//4.그 이미지 뷰에 이미지를 세팅하기
			imageView.setImageResource(imageRes);
			return layout;
		}
		
	}
}

주석안으로 실행시 이렇게 에러가 난다.



for문으로 실행시


+ Recent posts