如何使用字符串获取drawable?

时间:2015-02-09 07:17:59

标签: android

我知道有些问题与我的完全相同。我看了一对,我一直在用这个: How can I convert String to Drawable。但是,当我在我的代码中使用此代码中的代码时,drawable始终为null。

他的代码:

int id = getResources().getIdentifier(name, "drawable", getPackageName());
Drawable drawable = getResources().getDrawable(id);

这是我的代码,这种情况一直在发生。图像视图位于正确的位置,但那里没有图像。当我使用调试器运行它时,变量id得到我认为正确的整数值,但我不知道如何确认它。

String[] images = currExercise.get_allImg().split(",");
int id = context.getResources().getIdentifier(images[0], "drawable", context.getPackageName());
Drawable drawable = context.getResources().getDrawable(id);
mainImage.setBackground(drawable);

有没有替代方法呢?非常感谢任何建议,谢谢。

我正在添加我的整个Adapter类

public class ExerciseAdapter extends BaseAdapter {

//song list and layout
private ArrayList<Exercise> exercises;
private LayoutInflater exerciseInf;
private Context context;
private int screenWidth;

我正在传递上下文。这是你的意思吗?

//constructor
public ExerciseAdapter(Context c, ArrayList<Exercise> allExercises, int sw){
    exercises=allExercises;
    exerciseInf=LayoutInflater.from(c);
    context = c;
    screenWidth = sw;
}

@Override
public int getCount() {
    return exercises.size();
}

@Override
public Object getItem(int arg0) {
    return null;
}

@Override
public long getItemId(int arg0) {
    return 0;
}

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

    //map to song layout
    LinearLayout exerciseLay = (LinearLayout)exerciseInf.inflate(R.layout.exercise, parent, false);
    //get title and artist views

    ImageView exerciseMainImage = (ImageView)exerciseLay.findViewById(R.id.exerciseMainImage);
    exerciseMainImage.getLayoutParams().width = (int)Math.floor(screenWidth * .3);
    exerciseMainImage.getLayoutParams().height = (int)Math.floor(screenWidth * .3);
    LinearLayout exerciseContent = (LinearLayout)exerciseLay.findViewById(R.id.exerciseContent);
    exerciseContent.getLayoutParams().width = (int)Math.floor(screenWidth * .7);
    TextView titleView = (TextView)exerciseContent.findViewById(R.id.exerciseName);
    TextView entryView = (TextView)exerciseContent.findViewById(R.id.exerciseDescription);


    Exercise currExercise = exercises.get(position);

    String[] images = currExercise.get_allImg().split(",");
    /*Original*///exerciseMainImage.setImageResource(context.getResources().getIdentifier(images[0], "drawable", context.getPackageName()));
    int id = context.getResources().getIdentifier(images[0], "drawable", context.getPackageName());
    Drawable drawable = context.getResources().getDrawable(id);

    /*Debug*///Drawable drawable = context.getResources().getDrawable(R.drawable.backlifts1);

    exerciseMainImage.setBackground(drawable);

    titleView.setText(currExercise.get_exerciseName());
    entryView.setText(currExercise.get_description());

    exerciseLay.setTag(position);
    return exerciseLay;
}

}

0 个答案:

没有答案