3
TextView textView = new TextView(this);
        textView.setText(R.string.textView);
        textView.setId(View.generateViewId());


Button blueButton = new Button(this);
        blueButton.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View view) {
// I can't textView.getId() because textView isn't in this scope
                            TextView textView = (TextView) findViewById(textView.getId());
                            textView.setText("You clicked the Button!");

                        }
                    }
            );

My question is: how do I generate an Id, without just hardcoding some magic number

ie: textView.setId(1);

while still being able to actually access the Id if the variable's scope has died.

Answer: You can use blueButton.setTag(textView) and then in the onClick(View view) method, you can call view.getTag();

Josh Suttenberg
  • 99
  • 1
  • 10
  • 7
    Does [this](http://stackoverflow.com/questions/1714297/android-view-setidint-id-programmatically-how-to-avoid-id-conflicts) question answer any of your concerns? – Vucko Jun 22 '16 at 21:28
  • https://developer.android.com/reference/android/view/View.html#generateViewId() – samgak Jun 22 '16 at 23:03
  • is "outside the scope of onClick" your only concern? You could move the view declaration to have appropriate scope or have a viewIdMapper object - be careful of memory leaks. – Jim Jun 22 '16 at 23:27
  • @Vucko I saw that question that you posted, but unless I'm missing something I don't believe that fully answered my question. I don't want to set the Id to some some magic number, because that doesn't feel like it's good practice, and android studio underlines the number in red, so maybe that's why I think it's bad. If I use View.generateId() I can't actually access that Id because of the scope of the variable. The same applies for setting a tag. – Josh Suttenberg Jun 23 '16 at 13:23
  • Actually blueButton.setTag(textView); works. I didn't realize that "view" public void onClick(View view) was the button itself. I tried to bluebutton.getTag, but the only way to do that would be if the button was final, which I didn't want. It works just fine if I use view.getTag(); Thank you! I'll edit the answer into my post – Josh Suttenberg Jun 23 '16 at 13:34

2 Answers2

1

You have to instantiate the TextView outside the handler onClick.

TextView tv;

//onCreate
tv = (TextView) findView...

tv.setOnClickListener(new ...)
//onClick
tv.setText("");

And you refer to an xml id this way :

findViewById(R.id.myTextView);
Alexandre Martin
  • 1,472
  • 5
  • 14
  • 27
-3

To access TextView in that scope, change it to:

public static Textview myTextView;
ESPA_NETwork
  • 165
  • 2
  • 14