본문 바로가기
모바일개발(Mobile Dev)/안드로이드개발(Android)

ListView SimpleAdapter

by 테크한스 2016. 8. 13.
반응형



    MainActivity.java

package com.example.listview_dynamic_test;


import java.util.ArrayList;


import java.util.HashMap;


import android.os.Bundle;


import android.app.Activity;


import android.view.Menu;


import android.widget.ArrayAdapter;


import android.widget.ListView;


import android.widget.SimpleAdapter;




public class MainActivity extends Activity {



ListView listView;

@Override


protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);


setContentView(R.layout.activity_main);


//리스트 동적생성,  여러개 추가 가능!

ArrayList<Member> list = new ArrayList<Member>();

list.add(new Member("01","루피"));


list.add(new Member("02","조로"));


list.add(new Member("03","나미"));


list.add(new Member("04","쵸파"));


list.add(new Member("05","상디"));


//list를 map화 시킴

ArrayList<HashMap<String, String>>mapList = new ArrayList<HashMap<String,String>>();

for(Member m : list){



HashMap  map  = new HashMap();


//id와 name을 꺼내서 map타입으로 변경.


map.put("id", m.id);


map.put("name", m.name);


mapList.add(map);

}


listView = (ListView)findViewById(R.id.list);


SimpleAdapter adapter = 


new SimpleAdapter(this, 


//string값을 가져옴.


mapList, 


android.R.layout.simple_list_item_2, 


//자원


new String[]{"id","name"}, 


//view 1. 첫번째 view를 뿌려줌, 2. 두번째 view를 뿌려줌


new int[]

{android.R.id.text1,android.R.id.text2});


listView.setAdapter(adapter);


}

}


//따로 생성하는 것이 아니라 하나의 activity안에 Member클래스를 정의

class Member{


String id;


String name;


public Member(String id, String name){


this.id = id;


this.name = name;

}

}


    activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"


    xmlns:tools="http://schemas.android.com/tools"


    android:layout_width="match_parent"


    android:layout_height="match_parent"


    tools:context=".MainActivity" >


    <ListView


        android:id="@+id/list"


        android:layout_width="match_parent"


        android:layout_height="wrap_content"


        android:layout_alignParentLeft="true"


        android:layout_alignParentTop="true" >


    </ListView>


</RelativeLayout>


반응형