如何根据数据库填充数据将图像源设置为listView

时间:2012-07-13 15:30:47

标签: android database android-listview imageview android-viewbinder

基本上我要做的是根据我从预先创建的数据库获取的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的新手,我真的很感激,如果可以告诉我我的错误或者是否有更好的方法来实现这一点。提前谢谢。

0 个答案:

没有答案
相关问题