2012-03-04 26 views
6

Tôi có một bộ điều hợp con trỏ tùy chỉnh và tôi muốn đặt một hình ảnh vào một ImageView trong một ListView.Lấy hình ảnh tài nguyên theo tên vào bộ điều hợp con trỏ tùy chỉnh

Mã của tôi là:

public class CustomImageListAdapter extends CursorAdapter { 

    private LayoutInflater inflater; 

    public CustomImageListAdapter(Context context, Cursor cursor) { 
    super(context, cursor); 
    inflater = LayoutInflater.from(context); 
    } 

    @Override 
    public void bindView(View view, Context context, Cursor cursor) { 
    // get the ImageView Resource 
    ImageView fieldImage = (ImageView) view.findViewById(R.id.fieldImage); 
    // set the image for the ImageView 
    flagImage.setImageResource(R.drawable.imageName); 
    } 

    @Override 
    public View newView(Context context, Cursor cursor, ViewGroup parent) { 
    return inflater.inflate(R.layout.row_images, parent, false); 
    } 
} 

Đây là tất cả OK nhưng tôi muốn để có được tên của hình ảnh từ cơ sở dữ liệu (con trỏ). Tôi đã thử với

String mDrawableName = "myImageName"; 
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName()); 

Nhưng trở lại báo lỗi: "The getResources() phương pháp là undefined cho các loại CustomImageListAdapter"

+0

Nếu bạn muốn nhận được từ Cursor tại sao bạn không gọi 'cursor.getString' thay thế. Và hình ảnh của bạn được lưu ở đâu? –

Trả lời

13

Bạn chỉ có thể làm một cuộc gọi getResources() trên một đối tượng Context. Kể từ khi constructor CursorAdapter có tham chiếu như vậy, chỉ cần tạo một thành viên lớp học theo dõi nó để bạn có thể sử dụng nó trong (có lẽ) bindView(...). Có thể bạn sẽ cần nó cho getPackageName().

private Context mContext; 

public CustomImageListAdapter(Context context, Cursor cursor) { 
    super(context, cursor); 
    inflater = LayoutInflater.from(context); 
    mContext = context; 
} 

// Other code ... 

// Now call getResources() on the Context reference (and getPackageName()) 
String mDrawableName = "myImageName"; 
int resID = mContext.getResources().getIdentifier(mDrawableName , "drawable", mContext.getPackageName()); 
+0

+1 bạn đánh bại tôi. :) – Squonk

+0

Cảm ơn "MH". cho giải pháp. (cũng để "MisterSquonk") – Cuarcuiu

+0

Tại sao bạn có thể sử dụng getResources() mà không cần thêm ngữ cảnh bên trong một Activity? Cảm ơn. – Ricardo

Các vấn đề liên quan