毎回そのロジックを入れるのも馬鹿らしいので、それ用のAdapterを作成しています。
以下にコードを載せるので、よろしかったら使ってください。
継承したAdapterクラスを作って、それをListViewにセットすればOKです。
ネーミングセンスが気に入らないときはリファクタリングをどうぞ。
import java.util.List;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
abstract public class EvenOddArrayAdapter<t> extends ArrayAdapter<t> {
private int listOddColor;
private int listEvenColor;
protected LayoutInflater inflater;
public EvenOddArrayAdapter(Context context, int textViewResourceId, List<t> objects, int oddColor, int evenColor) {
super(context, textViewResourceId, objects);
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resources resources = context.getResources();
listOddColor = resources.getColor(oddColor);
listEvenColor = resources.getColor(evenColor);
}
public EvenOddArrayAdapter(Context context, List<t> objects, int oddColor, int evenColor) {
this(context, 0, objects, oddColor, evenColor);
}
/**
* @see android.widget.ArrayAdapter#getView(int, android.view.View,
* android.view.ViewGroup)
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView != null) {
convertView.setBackgroundColor((position & 1) == 1 ? listOddColor : listEvenColor);
}
return convertView;
}
}
注意事項
- コンストラクタの引数 oddColorとevenColorはリソースIDです。
- getView()ではsuper.getView()を呼び出していないため、行にフォーカスが当たったときなどに表示が変えられないという欠点があります。(うまいやり方がないものか。。。)
0 件のコメント:
コメントを投稿