2017-03-24 1 views
0

Android 리소스 ID를 가져오고 ImageView src를 JSON 배열의 특정 ID로 설정하려고합니다.어댑터의 문자열에서 Android 리소스 ID 가져 오기

나는 다음과 같은 코드

String str = mDataset.get(position).icon_res.substring(0, mDataset.get(position).icon_res.lastIndexOf('.')); 
     int res = Resources.getSystem().getIdentifier("ic_" + str, "drawable", this.getClass().getPackage().getName()); 
     if(res == 0) 
     { 
      Log.d("is null", "null"); 
      Log.d("string = ", "ic_" + str); 
      Log.d("package", this.getClass().getPackage().getName()); 
     } 

을 사용하고 그러나 0 패키지 이름이 올바른지 보인다 어떤 이유에서가 입술 int로 감지 것, 문자열은 정확하지만 어떤 이유로 올바른 드로어 블 리소스를 찾는 아니에요. 여기서 내가 뭘 잘못하고 있니?

편집 : 관리가

Full adapter code 

package com.xyz 

import android.app.Activity; 
import android.app.Application; 
import android.content.Context; 
import android.content.res.Resources; 
import android.graphics.drawable.Drawable; 
import android.media.Image; 
import android.support.constraint.ConstraintLayout; 
import android.support.v7.widget.RecyclerView; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ImageView; 
import android.widget.RelativeLayout; 
import android.widget.TextView; 

import java.util.ArrayList; 
import java.util.List; 

/** 
* Created by Kreso on 23.3.2017.. 
*/ 

public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder>{ 


    private List<Category> mDataset; 
    private Context context; 

    public CategoryAdapter(List<Category> categoriesList) { 
     mDataset = categoriesList; 
    } 


    // Provide a reference to the views for each data item 
    // Complex data items may need more than one view per item, and 
    // you provide access to all the views for a data item in a view holder 
    public class ViewHolder extends RecyclerView.ViewHolder { 
     // each data item is just a string in this case 
     public TextView txtHeader; 
     public ConstraintLayout holderLayout; 
     public ImageView icon; 

     public ViewHolder(View v) { 
      super(v); 
      txtHeader = (TextView) v.findViewById(R.id.firstLine); 
      holderLayout = (ConstraintLayout) v.findViewById(R.id.itemHolder); 
      icon = (ImageView) v.findViewById(R.id.icon); 
      context = v.getContext(); 
     } 
    } 

    /*public void add(int position, String item) { 
     mDataset.add(position, item); 
     notifyItemInserted(position); 
    }*/ 

    public void remove(int position) { 
     mDataset.remove(position); 
     notifyItemRemoved(position); 
     notifyItemRangeChanged(position, mDataset.size()); 
    } 

    // Provide a suitable constructor (depends on the kind of dataset) 
    /* public CategoryAdapter(ArrayList<String> myDataset) { 
     mDataset = myDataset; 
    }*/ 

    // Create new views (invoked by the layout manager) 
    @Override 
    public CategoryAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, 
                int viewType) { 
     // create a new view 
     View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item_row, parent, false); 
     // set the view's size, margins, paddings and layout parameters 
     ViewHolder vh = new ViewHolder(v); 
     return vh; 
    } 

    // Replace the contents of a view (invoked by the layout manager) 
    @Override 
    public void onBindViewHolder(ViewHolder holder, final int position) { 
     // - get element from your dataset at this position 
     // - replace the contents of the view with that element 
    final String name = mDataset.get(position).name; 
     holder.txtHeader.setText(mDataset.get(position).name); 
     //holder.icon.setImageResource(R.drawable.ic_beer); 
     String str = mDataset.get(position).icon_res.substring(0, mDataset.get(position).icon_res.lastIndexOf('.')); 
     int res = context.getResources().getSystem().getIdentifier("ic_" + str, "drawable", context.getPackageName()); 
     if(res == 0) 
     { 
      Log.d("is null", "null"); 
      Log.d("string = ", "ic_" + str); 
      Log.d("package", this.getClass().getPackage().getName()); 
     } 

     holder.icon.setImageResource(res); 
     holder.holderLayout.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      remove(position); 
     } 
    }); 

} 

    // Return the size of your dataset (invoked by the layout manager) 
    @Override 
    public int getItemCount() { 
     return mDataset.size(); 
    } 

} 
+0

주 당신의 어댑터의 전체 코드 –

+0

'Resources.getSystem()'은 패키지의'Resources'가 아닙니다. 그것이 귀하의 식별자를 찾는 것이 아닙니다. –

+0

@MikeM. 그럼 내가 무엇을 사용해야합니까? 그것은 다소 혼란스럽고 나는 이것을 처음으로하고 있습니다. 내 대답이 내게 필요한 결과를 주었지만, 당신의 영혼이 더 좋으면 배경에 대해 더 알고 싶습니다. –

답변

1

사용이 코드를 사용하여 해결하기 위해 :

int res = context.getResources().getIdentifier("ic_" + str, "drawable", context.getPackageName()); 
0

는 자원에서 이미지를 얻을, 약간 다른 접근 방식

// Remove file extension 
     String str = mDataset.get(position).icon_res.substring(0, mDataset.get(position).icon_res.lastIndexOf('.')); 
     // Replace - with underscore _ 
     str = str.replace("-", "_"); 

     int res = 0; 
     // Try to find the resource with that name (icons in drawable folder) 
     try { 
      res = R.drawable.class.getField("ic_" + str).getInt(null); 
     } catch (IllegalAccessException e) { 
      e.printStackTrace(); 
     } catch (NoSuchFieldException e) { 
      // if no icon is found 
      holder.icon.setImageResource(R.drawable.ic_coffee); 
     } 
     // Set icon resource 
     holder.icon.setImageResource(res); 
관련 문제