2016-05-10 3 views
0

Привет, я не могу найти solutiıon для моего вопроса. Я беру имя изображения из db. И тогда я должен дать tat string для image.setImageResource. Есть много ответов, которые включают getResources().getIdentifier( Но getResoruces() не работает. Я получаю ошибку: Ошибка: (40, 21) ошибка: не удается найти метод символов getResources() Как я могу решить эту проблему.Получение идентификатора для имени

public class ReceivedItemAdapter extends ArrayAdapter<ReceivedItem> { 

    public ReceivedItemAdapter(Context context, ArrayList<ReceivedItem> items){ 
     super(context,R.layout.row_item_received,items); 
    } 

    public View getView(int position, View convertView, ViewGroup parent) { 

     View customView = LayoutInflater.from(this.getContext()) 
      .inflate(R.layout.row_item_received, parent, false); 

     ReceivedItem item = getItem(position); 
     TextView textName = (TextView) customView.findViewById(R.id.nameTextView); 
     TextView textCalorie = (TextView) customView.findViewById(R.id.calorieTextView); 
     ImageView imageView = (ImageView) customView.findViewById(R.id.imageView); 
     textName.setText(item.getName()); 
     textCalorie.setText(item.getCalorie()+ " cal"); 
     String mDrawableName = item.getImageName(); 
     int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName()); 
     imageView.setImageResource(resID); 
     customView.setTag(item.getId()); 
     return customView; 
    } 
} 

Я использую этот код в ListView адаптер класса

+0

пожалуйста наклеить, как и где вы звоните GetResources() –

+1

' getResources() 'работает. но вам нужен «контекст», чтобы получить доступ к этому методу –

+0

Как добавить контекст? – berkt

ответ

1

Оба ответа верны и работа.

Но легче назвать

int resID = customView.getContext().getResources().getIdentifier(mDrawableName , "drawable", getPackageName()); 

Вы можете сделать это, так как каждый вид имеет ссылку на контекст

public final Context getContext()

Returns the context the view is running in, through which it can access the current theme, resources, etc.

Returns Context The view's Context.

+0

я знаю ID: 7614 java.lang.OutOfMemoryError: Не удалось выделить распределение 17640012 байт с 5184936 свободных байтов и 4Мб до ООМ на dalvik.system.VMRuntime.newNonMovableArray (Native Method) – berkt

+0

Это другая проблема, но вероятно, ваши изображения, которые вы пытаетесь загрузить, являются большими –

+0

Спасибо, я справляюсь с этой проблемой, делая их меньше. Есть ли какое-то решение вместо того, чтобы делать меньше? – berkt

1

Пожалуйста, пост код, прежде чем мы можем вам помочь.

Если вы хотите получить доступ к внешним ресурсам getResources и активности или тому подобное, вам нужно получить ссылку на контекст, а затем вызвать context.getResources.

Просто позвоните customView.getContext(). GetResources()

+0

Я редактирую свой вопрос. Я хочу получить его от адаптера listview. – berkt

1

Вы должны держать экземпляр контекста внутри адаптера, а затем вызвать context.getResources()

public class ReceivedItemAdapter extends ArrayAdapter<ReceivedItem> { 

private final Context context; 

public ReceivedItemAdapter(Context context, ArrayList<ReceivedItem> items){ 
    super(context,R.layout.row_item_received,items); 
    this. context = context; 
} 

public View getView(int position, View convertView, ViewGroup parent) { 

    View customView = LayoutInflater.from(this.getContext()) 
      .inflate(R.layout.row_item_received, parent, false); 

    ReceivedItem item = getItem(position); 
    TextView textName = (TextView) customView.findViewById(R.id.nameTextView); 
    TextView textCalorie = (TextView) customView.findViewById(R.id.calorieTextView); 
    ImageView imageView = (ImageView) customView.findViewById(R.id.imageView); 
    textName.setText(item.getName()); 
    textCalorie.setText(item.getCalorie()+ " cal"); 
    String mDrawableName = item.getImageName(); 
    int resID = context.getResources().getIdentifier(mDrawableName , "drawable", getPackageName()); 
    imageView.setImageResource(resID); 
    customView.setTag(item.getId()); 
    return customView; 
} 
Смежные вопросы