たぼさんの部屋

いちょぼとのんびり

ListView:SimpleAdapterで作る2段レイアウト(xmlレイアウト使用)

複雑なレイアウトのListViewを作るには

  • SimpleAdapterを使うとArrayAdapterでは難しい複雑なデータをListViewにヒモつけることが可能です。
    リストビューのそれぞれの行が複数の項目を持っている場合には、この方法を使用することにより自由なレイアウトで表示できます。
  • 表示用のレイアウトは別途xmlファイルで構成します[例:layout_row.xml]
  • SimpleAdapterへのデータのヒモ付けはHashMap型のArrayListを使います。

f:id:donsuka_kk:20131002134458p:plain

Main.java

package com.efolab;

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

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class Main extends Activity {

	/** Called when the activity is first created. */
	Context context;
	ListView lv;
	//データを格納するためのArrayList
	ArrayList<HashMap<String,String>> collection = new ArrayList<HashMap<String,String>>();
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	
	    // TODO Auto-generated method stub
	    context = getApplicationContext();
	    lv = new ListView(context);
	    setContentView(lv);
	    
	    lv.setBackgroundColor(Color.BLACK);		//背景色指定
	    
	    String mString[] = { "aaa", "abc", "bbb", "ccc","hoge","moeno","souichiro","yukiko","ore","hahah","hene" };
	    
	    
	    for(int i=0;i<mString.length;i++){
	    	//ハッシュマップにデータを格納していく
	    	HashMap<String,String> map = new HashMap<String,String>();
	    	map.put("no", ""+i);
	    	map.put("name", mString[i]);
	    	//作成したmapをcollectionに格納
	    	collection.add(map);
	    }
	    
	    /*
	     * 作成したcollectionとカスタムマイズしたレイアウト
	     * layout_row.xmlを
	     * ヒモつけたSimpleAdapterを
	     * 作成する
	     */
	    SimpleAdapter adapter = new SimpleAdapter(context, collection, R.layout.layout_row, new String[]{"no","name"}, new int[]{R.id.textView1,R.id.textView2});
	    
	    lv.setAdapter(adapter);
	}

}

res/layout/layout_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

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

    <TextView
        android:id="@+id/textView2"
        android:layout_width="217dp"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textSize="12dp" />

</LinearLayout>