简体   繁体   中英

Class arguments inside method java

I can't find info about that. Is it possible and if yes then how to use class arguments inside the method?

public static class allDragons {
    String name;
    Integer resource;
}

public void MethodName() {
    dragonImage.setImageResource(rareDragon.resource); // here I would like to refer to the argument, but it doesn't work. 
}

ImageView dragon;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dragon);

    dragonImage = findViewById(R.id.dragonimg);

    allDragons rareDragon = new allDragons();

    rareDragon.number = 1;
    rareDragon.resource = (R.drawable.dragon);
        
    ...

I found that I should use something like: setImageResource(allDragons().rareDragon.resource) , but it still not work. I tried many combinations and modifiers but still failed. How? Possible? Other way?

Maybe I'm completely wrong - it's not really clear to me what you're trying to achieve, but maybe this helps you to find an answer.

AllDragons is a static class definition. You can create instances of it (like you did in method onCreate() ) and assign it to a member instead of a local variable:

public class OuterClass {

    public static class AllDragons {
        String name;
        Integer resource;
    }

    ImageView dragon;
    
    // In order to access "rareDragon" in any method of this class,
    // you need to create a member
    AllDragons rareDragon;

    public void methodName() {
        dragonImage.setImageResource(rareDragon.resource); 
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dragon);

        dragonImage = findViewById(R.id.dragonimg);

        rareDragon = new allDragons();

        rareDragon.number = 1;
        rareDragon.resource = (R.drawable.dragon);
    }
}

PS: I adapted your class/field/method names. In Java there a some Coding Conventions existing:

  • Class names should start with a capital letter
  • Method names and fields should start with a lower-case letter
  • Constants should be written completely in upper-case letters

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