2013-10-28 5 views
1

나는 안드로이드 프로그래밍 초보자이며이 간단한 작업에 엄청난 어려움을 겪고 있습니다.Listview에 Hashmap 배열 추가

은 내가 ArrayList를 가지고 :

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

을 그리고 난 ListView가 각 키/값 쌍을 추가 할 수 있습니다.

어떻게 ListView에 추가합니까? 나는 어댑터를 온라인으로 사용하는 것에 대한 수많은 설명을 보았다.하지만 그들은 모두 내가 아는 변수를 사용한다. 그런 다음

public class MyAdapter extends BaseAdapter { 

    private Activity activity; 
    private HashMap<String, String> map; 

    public MyAdapter(Activity activity, HashMap<String, String> map) { 
     this.activity = activity; 
     this.map = map; 
    } 

    public int getCount() { 
     return map.size(); 
    }  

    public View getView(final int position, View convertView, ViewGroup parent) { 
     if (convertView == null) { 
      LayoutInflater inflater = (LayoutInflater) activity 
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      convertView = inflater.inflate(R.layout.my_list_item, 
        null); 
     } 

      // Recommended to use a list as the dataset passed in the constructor. 
      // Otherwise not sure how you going to map a position to an index in the dataset. 
      String key = // get a key from the HashMap above 
      String value = map.get(key); 

      TextView keyView = convertView.findViewById(R.id.item_key); 
      keyView.setText(key); 

      TextView valueView = convertView.findViewById(R.id.item_value); 
      valueView .setText(value); 

     return convertView; 
    }  
} 

당신의 ListView는, setAdapter 방법으로 전달할 :

답변

2

자신의 어댑터 클래스를 구축

MyAdapter myAdapter = new MyAdapter(this, map); 
ListView listview = (ListView) findViewById(R.id.listview); 
listview.setAdapter(myAdapter); 

샘플 레이아웃/my_list_item.xml :

<LinearLayout xmlns:android:http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
> 

    <TextView 
     android:id="@+id/item_key" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
    /> 

    <TextView 
     android:id="@+id/item_value" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
    /> 
</LinearLayout> 
+0

는 R 무엇입니까 .layout.my_list_item? 목록보기 만 있습니다. –

+0

내 항목으로 뷰를 채우는 방법을 잘 모르겠습니다. –

+0

행을 어떻게 보이게 할 것인지에 대한 사용자 정의 레이아웃을 직접 만들 수 있습니다. 그건 R.layout.my_list_item입니다. –