Android - 无法在自定义适配器中设置我的imageView

时间:2013-11-15 18:15:15

标签: android imageview

我正在尝试根据字符串值设置我的imageview。但图像从未设定。如果我在这里做错了,请指导我。感谢

这是我的代码:

public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    getExpense expense = objects.get(position);
    EventController controller = new EventController(ctx);
    View view = convertView;
    if (view == null) {
        view = lInflater.inflate(R.layout.view_expense_entry, parent, false);
    }
    TextView expenseId = (TextView)view.findViewById(R.id.expenseId);
    expenseId.setText(expense.getExpenseId());
    TextView expenseName = (TextView)view.findViewById(R.id.expenseName);
    expenseName.setText(expense.getExpenseName());
    TextView expenseQuantity = (TextView)view.findViewById(R.id.expenseQuantity);
    expenseQuantity.setText("Quantity : x" + expense.getExpenseQuantity());
    ImageView expenseImage = (ImageView)view.findViewById(R.id.ivtype);
    String expenseType = controller.getExpenseType(expenseId.getText().toString());
    if (expenseType.equals("Food")){
        expenseImage.setImageResource(R.drawable.food);
    }
    else if (expenseType.equals("Beverage")){
        expenseImage.setImageResource(R.drawable.drink);
    }
    else if (expenseType.equals("Dessert")){
        expenseImage.setImageDrawable(ctx.getResources().getDrawable(R.drawable.dessert));
    }
    else if (expenseType.equals("Set")){
        expenseImage.setImageDrawable(ctx.getResources().getDrawable(R.drawable.set));
    }

    return view;
}

1 个答案:

答案 0 :(得分:0)

除了我上面关于确保满足IF条件的评论。您正在使用需要整数的setImageResource,然后您正在使用getDrawable。所以你的代码不一致。

试试这个:

int resourceId = 0;

if (expenseType.equals("Food")){
    resourceId = ctx.getResources().getIdentifier("Food","drawable",ctx.getPackageName());
}
else if (expenseType.equals("Beverage")){
    resourceId = ctx.getResources().getIdentifier("drink","drawable",ctx.getPackageName());
}
else if (expenseType.equals("Dessert")){
    resourceId = ctx.getResources().getIdentifier("dessert","drawable",ctx.getPackageName());
}
else if (expenseType.equals("Set")){
    resourceId = ctx.getResources().getIdentifier("set","drawable",ctx.getPackageName());
}
expenseImage.setImageResource(resourceId);