【问题标题】:What is the difference between usage of setViewBinder/setViewValue and getView/LayoutInflater?setViewBinder/setViewValue 和 getView/LayoutInflater 的用法有什么区别?
【发布时间】:2011-09-08 21:18:07
【问题描述】:
看起来有两种可能的方法可以更改 ListView 行中的内容:
-
使用setViewBinder/setViewValue:
myCursor.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
int viewId = view.getId();
switch(viewId) {
case R.id.icon:
// change something related to the icon here
-
使用getView/LayoutInflater:
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) parent.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
itemView = inflater.inflate(R.layout.list_row, null);
} else {
itemView = convertView;
}
ImageView imgViewChecked = (ImageView) itemView
.findViewById(R.id.icon);
// change something related to the icon here
这两种方法有什么区别?
【问题讨论】:
标签:
android
android-listview
layout-inflater
android-viewbinder
【解决方案1】:
您可以同时使用它们来完成相同的任务。
ViewBinder 系统是由 SimpleCursorAdapter 添加的,让您更轻松,因此您不必编写整个 getView 代码。事实上,SimpleCursorAdapter 只是通过调用 setViewValue 方法来实现 getView(以及标准的样板错误检查和膨胀)
我在 SimpleCursorAdapter 中附上了 Android 源代码用于 getView 的实现:
public View getView(int position, View convertView, ViewGroup parent) {
if (!mDataValid) {
throw new IllegalStateException(
"this should only be called when the cursor is valid");
}
if (!mCursor.moveToPosition(position)) {
throw new IllegalStateException("couldn't move cursor to position "
+ position);
}
View v;
if (convertView == null) {
v = newView(mContext, mCursor, parent);
} else {
v = convertView;
}
bindView(v, mContext, mCursor);
return v;
}
public void bindView(View view, Context context, Cursor cursor) {
final ViewBinder binder = mViewBinder;
final int count = mTo.length;
final int[] from = mFrom;
final int[] to = mTo;
for (int i = 0; i < count; i++) {
final View v = view.findViewById(to[i]);
if (v != null) {
boolean bound = false;
if (binder != null) {
bound = binder.setViewValue(v, cursor, from[i]);
}
if (!bound) {
String text = cursor.getString(from[i]);
if (text == null) {
text = "";
}
if (v instanceof TextView) {
setViewText((TextView) v, text);
} else if (v instanceof ImageView) {
setViewImage((ImageView) v, text);
} else {
throw new IllegalStateException(
v.getClass().getName()
+ " is not a "
+ " view that can be bounds by this SimpleCursorAdapter");
}
}
}
}
}