1

Morning!

I am very new to learning android and indeed Java, I am building an app to track rugby scores for a match between two teams. It works fine, but I'm annoyed by come of the code I have written. Basically, I am calling a different method for each onClick - which I guess is fine, but each of those methods calls 2 different display methods, which I am looking to streamline if I can.

Example:

public void try_home(View v) {
    scoreHome += 5;
    tryHome++;
    displayForTeamA(scoreHome);
    displayTryHome(tryHome);
}

And my reset is even worse:

public void reset(View v) {
    displayForTeamA(scoreHome = 0);
    displayForTeamB(scoreAway = 0);
    displayTryHome(tryHome = 0);
    displayTryAway(tryAway = 0);
    displayConvertHome(convertHome = 0);
    displayConvertAway(convertAway = 0);
    displayFieldHome(fieldHome = 0);
    displayFieldAway(fieldAway = 0);
    displayPenHome(penHome = 0);
    displayPenAway(penAway = 0);

}

So this is what I am trying to do, but obviously doesn't work because findViewById() want's an int.. am I on the right track, is there a way to do this?

public void display(int val, String textView) {
    String viewID = "R.id." + textView;
    TextView scoreView = (TextView) findViewById(viewID);
    scoreView.setText(String.valueOf(val));
}

Hopefully I am making sense and my question is concise enough! Thank you in advance for any and all help

Jay Gale
  • 25
  • 4

1 Answers1

0
int viewID = context.getResources().getIdentifier(textView, "id", context.getPackageName())

should do the trick (replacing the first line inside your display method).

kalabalik
  • 3,792
  • 2
  • 21
  • 50
  • awesome! what is context? I dont have a var for that, and I assume the textview is the string im passing to the method? Thank you! – Jay Gale Sep 29 '17 at 11:16
  • Where is the `display` method located? If it is inside your `Activity` just use `this` instead of `context`, if it is somewhere else it need a reference to your `Activity`. See: https://stackoverflow.com/a/15488321/3356270 – kalabalik Sep 29 '17 at 11:20
  • ah, wonderful, yeah I only have one class, the MainActivity, thanks again! (Can't +1 your answer because noob, sorry) – Jay Gale Sep 29 '17 at 11:24
  • Kind of irrelevant, but now I can do that, going to see if I can pass an array and loop, so only need one display() call (for learning purposes) – Jay Gale Sep 29 '17 at 11:26
  • You cannot upvote my answer, but you can accept it as the correct answer: just click the check. – kalabalik Sep 29 '17 at 11:31