記事

カスタムViewListでリスト一覧を作成する

Book.java

public class Book {
	private String author;
	private String title;
	
	public Book(String title, String author){
		this.author = author;
		this.title = title;
	}
	public String getAuthor() {
		return author;
	}

	public String getTitle() {
		return title;
	}
}

SampleAdapter.java

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class SampleAdapter extends ArrayAdapter<Book> {

	private Context _context;
	private int _textViewResourceId;
	private List<Book> _items;
	private LayoutInflater _inflater;

	public SampleAdapter(Context context, int textViewResourceId, List<Book> items) {
		super(context, textViewResourceId, items);

		_context = context;
		_textViewResourceId = textViewResourceId;
		_items = items;

		_inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view;
		if (convertView != null) {
			view = convertView;
		} else {
			view = _inflater.inflate(_textViewResourceId, null);
		}

		Book item = _items.get(position);

		((TextView) view.findViewById(R.id.title)).setText(item.getTitle());
		((TextView) view.findViewById(R.id.isbn)).setText(item.getAuthor());

		return view;
	}
}
import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		ArrayList<Book> books = new ArrayList<Book>();
		books.add(new Book("ナルト","岸本斉史"));
		books.add(new Book("コナン","青山剛昌"));
		books.add(new Book("ワンピース","尾田栄一郎"));
		books.add(new Book("デスノート","小畑健"));
		
		SampleAdapter adapter = new SampleAdapter(this, R.layout.samplerow, books);

		ListView lv = (ListView) findViewById(R.id.booklist);
		lv.setAdapter(adapter);

	}

}

samplerow.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">

	<TextView
		android:id="@+id/title"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:textSize="19sp"
		android:text="hoge"
		/>
	<TextView
		android:id="@+id/isbn"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:textSize="15sp"
		android:text="hoge"
		/>
</LinearLayout>

なんだろ、全然理解できない・・