Android:Imageview根据edittext选项显示图像

时间:2011-06-03 05:15:29

标签: android imageview android-edittext

我的res / drawable文件夹中有10个动物图像,我想根据编辑文本选项逐个显示图像。我的意思是在编辑文本中,当我们输入我们的体重时,根据体重的范围(如果体重在60-70图像视图之间显示虎),每个体重图像视图显示不同的动物(根据范围)具有不同的声音。由于我是android新手,我无法解决这个问题,我们如何实现这个?有什么想法吗?

总是感谢帮助......!

2 个答案:

答案 0 :(得分:2)

根据您的Edittext值,您可以在下面的函数中传递该值

private void displayImg(int value){
    ImageView im = (ImageView)findViewById(R.id.img1);
    if (value >= 0 && value < 10){
        im.setBackgroundResource(R.drawable.animal1);
    }else if (value >=10 && value <20){
        im.setBackgroundResource(R.drawable.animal2);
    }
            ..... so on...
}

答案 1 :(得分:2)

ImageView imgAnimal = (ImageView)findViewById(R.id.image_animal);
EditText editWeight = (EditText)findViewById(R.id.edit_weight);
try {
    // get the weight, will throw an exception if
    // the EditText doesn't contain a valid integer
    int weight = Integer.parseInt(editWeight.getText().toString());
    // if you reach this, the conversion was successful, but you might want to
    // check for negative values, or values too small / too big and warn the user
    // if you want to change the image based on a range,
    // the only way is to use chained if's
    if (weight >= 60 && weight <= 70)
        imgAnimal.setImageResource(R.drawable.tiger);
    else if (weight > 70 && weight <= 80)
        imgAnimal.setImageResource(R.drawable.some_animal);
    // and so on...
} catch (NumberFormatException nfe) {
    // the EditText does not contain a number, warn the user or something
}