简体   繁体   中英

How to shorten if x then y in java

I am trying to upload multiple images into 4 image views, I would like to use a for loop to do it.

ImageView view = defaultView;
String url = {"jpg1.png", "jpg2.png", "jpg3.png", "jpg4.png"};

    for (int i = 0; i < 4; i++) {
        if (i==0) {
            view = aView;
        }
        if (i==1) {
            view = bView;
        }
        if (i==2) {
            view = cView;
        }
        if (i==3) {
            view = dView;
        }

        Glide
                .with(this)
                .load("Website/folder/" + url[i])
                .override(widthpx, heigthpx)
                .into(view);

How could I use less if statements? Is this possible? Or is there a way to store variables inside an array? (like: Variables[] view = {default, aView, bView, cView, dView}

Thanks!

One possibility:

ImageView[] views = { aView, bView, cView, dView };
for (int i = 0; i < 4; i++) {
    ImageView view = views[i];
    Glide ........
}

Another:

glideMethod(aView, "jpg1.png");
glideMethod(bView, "jpg2.png");
glideMethod(cView, "jpg3.png");
glideMethod(dView, "jpg4.png");

where all the stuff that starts with Glide.with(........ is put into a method, and the method is given an appropriate name that describes what you're doing. (I have no idea what that code does, so I just called it glideMethod , but you'll need a better name.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM