使用String变量创建android imageview

时间:2017-09-06 15:18:26

标签: java android imageview

我想让用户添加一个新项目,用户可以输入项目名称,项目描述,项目价格等。让名称变量存储糖果,我在我的drawable中有一个糖果图像我可以像R.drawable.name那样引用R.drawable.candy ??任何人帮助请

public class item {
    String name;
    String desc;
    double price;
    int itemimage;

    public item(String name, String desc, double price) {
        this.name = name;
        this.desc = desc;
        this.price = price;

        itemimage = R.drawable.name;//my question is here
        //i want to have auto define the image of the item for later use
        // so i can do like set imageview of this item
        //i will have the image have same name with item name
        // for example my item name is candy
        //then i will have a image at the android drawable named candy
        //so in android to define this image is R.drawable.candy
        // can i do like R.drawable.name  <-- variable store with value candy
        // is it same with R.drawable.candy
    }
}//end class item

//another class
public class main {
    Arraylist<item> itemdatabase = new Arraylist<item>();

    Scanner input = new Scanner(System.in);

    System.out.print("Enter item name:");
    String itemname = input.nextLine();

    System.out.print("Enter item desc:");
    String itemdesc = input.nextLine();

    System.out.print("Enter item price:");
    double itemprice = input.nextDouble();

    itemdatabase.add(new

    item(itemname, itemdesc, itemprice);
}

2 个答案:

答案 0 :(得分:1)

您可以使用Resources.getIdentifier() method。对于R.drawable.candy,您可以像这样使用它:

int id = getResources().getIdentifier("candy", "drawable", getPackageName());
// now `id` == R.drawable.candy

此代码假设您在Activity内运行。如果没有,您需要访问Context个实例,以便拨打Context.getResources()Context.getPackageName()。这可能是这样的:

int id = mContext.getResources().getIdentifier("candy", "drawable", mContext.getPackageName());

答案 1 :(得分:0)

答案是否,你不能像R.drawable.name那样做