ListViewの表示を独自レイアウトで表示
使い道としては、画像つきリスト表示など
クックパッドやYouTubeみたいに
サムネイル表示などに使えそう
ListViewに独自レイアウトを表示するには
表示を司るAdapterクラスを拡張する必要がある
まずは、レイアウトファイルを作成して
項目用レイアウトを作成
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | < LinearLayout android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:orientation = "horizontal" > < ImageView android:id = "@+id/image" android:layout_width = "60dip" android:layout_height = "60dip" /> < TextView android:id = "@+id/text" android:layout_width = "" wrap_content android:layout_height = "wrap_content" android:choiceMode = "singleChoice" /> </ LinearLayout > |
android:choiceMode=”singleChoice”
は、単一行のみチェック可能にする
参考サイトは
http://blogand.stack3.net/archives/83
今回は、リストアイテムとして
画像と文字にしたかったので
60×60の画像と
文字の大きさにあわせるTextViewにしている
次に、Javaで独自レイアウトの設定
ListViewに独自レイアウトを設定するため
ArrayAdapterクラスを継承し
getView()をOverrideする
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | public class CustomAdapter extends ArrayAdapter<CustomData>{ private layoutInflater mlayoutInflater; public CustomAdapter(Context context, int textViewResourceId, List<CustomData> objects){ super (context,textViewResourceId, objects); mlayoutInflater = (layoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public View getView( int position, View convertView, ViewGroup parent){ //特定の行 position のデータを得る CustomData item = (CustomData)getItem(position); //同じ行に表示されるViewは使い回しされるので初回だけ生成 if ( null == convertView){ convertView = mlayoutInflater.inflate(R.layout.list_item, null ); } //データをViewの各widgetにセット ImageView imageView; imageView = (ImageView)findViewById(R.id.image); imageView.setImageBitmap(item.getTextData()); return convertView; } } |
これで、画像つきのリスト表示ができる