基本上我要做的是根据我从预先创建的数据库中获得的 id 将图像源动态设置为图像视图。这是我的 ListFragment:
public class teamsListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
String[] teams;
private SimpleCursorAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] projection = {DBAdapter.KEY_ROWID, DBAdapter.KEY_NAME};
String[] uiBindFrom = {DBAdapter.KEY_NAME};
int[] uiBindTo = {R.id.label};
getLoaderManager().initLoader(0, null, this);
adapter = new SimpleCursorAdapter(
getActivity().getApplicationContext(), R.layout.team_row,
null, uiBindFrom, uiBindTo, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
adapter.setViewBinder(VIEW_BINDER);
setListAdapter(adapter);
}
static final SimpleCursorAdapter.ViewBinder VIEW_BINDER = new SimpleCursorAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if(view.getId() != R.id.icon) return false;
ImageView teamIcon = (ImageView) view;
int idTeam = cursor.getInt(cursor.getColumnIndex(DBAdapter.KEY_ROWID));
switch(idTeam) {
case 1:
teamIcon.setImageResource(R.drawable.team1);
break;
case 2:
teamIcon.setImageResource(R.drawable.team2);
break;
}
return true;
}
};
}
这是我的 teamrow.xml
<ImageView
android:id="@+id/icon"
android:layout_width="30dp"
android:layout_height="24dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
/>
<TextView
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:lines="1"
android:text="@+id/TextView01"
android:textSize="24dp" />
问题是它不起作用,没有设置图像源。我认为是视图活页夹,但我是 android 新手,如果能告诉我我的错误或者是否有更好的方法来实现这一点,我真的很感激。提前致谢。