Android: Imageview showing an image according to edittext option

ε祈祈猫儿з 提交于 2020-01-16 00:44:07

问题


I have 10 animal images in my res/drawable folder and I want to show the images one by one according to the edit text options. I mean in the edit text when we enter our weight, according to the range of the weight (if weight is between 60-70 image view shows tiger) for each weight Image view shows different animal (according to range) with different sounds. As I am new to android I couldn't able to solve this, how can we Implement this? Any Idea?

Help is always appreciated....!


回答1:


As per your Edittext value you can pass that value in below function

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...
}



回答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
}


来源:https://stackoverflow.com/questions/6223232/android-imageview-showing-an-image-according-to-edittext-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!