2012年7月6日金曜日

ListViewの要素変更:SimpleAdapter



import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ListActivity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleAdapter;
import android.widget.TwoLineListItem;

public class AndroidListView004Activity extends  ListActivity {

 public class MySimpleAdapter extends SimpleAdapter {
      public MySimpleAdapter(Context context, List<Map<String, String>> items, int resource, String[] from, int[] to) {
          super(context, items, resource, from, to);
      }
  
      @Override
      public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
         
        TwoLineListItem v = (TwoLineListItem)view;
        v.getText1().setTextSize(30);
         
        if (position % 2 == 0) {
            view.setBackgroundColor(Color.BLACK);
        } else {
            view.setBackgroundColor(Color.DKGRAY);
            
        }
         
        return view;
      }
  }

 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        List<Map<String, String>> dataList = new ArrayList<Map<String,String>>();

        Map<String, String> data = new HashMap<String, String>();
        data.put("title", "タイトル欄");
        data.put("comment", "COMMENT欄");
        dataList.add(data);

        data = new HashMap<String, String>();
        data.put("title", "タイトル欄2");
        data.put("comment", "COMMENT欄");
        dataList.add(data);

        MySimpleAdapter adapter = new MySimpleAdapter(
                this,
                dataList,
                android.R.layout.simple_list_item_2,
                new String[] { "title", "comment" },
                new int[] { android.R.id.text1, android.R.id.text2 }
            );
        setListAdapter(adapter);
    }
}

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

    <ListView
        android:id="@id/android:list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

関連記事

0 件のコメント:

コメントを投稿