0

So I'm trying to get the user to be able to set an onClickListener on a button which will change a TextView upon clicking. However, this causes a final declaration error to appear because I am calling it from an inner class. I don't understand why it requires it to be set to a final, unchangeable variable. I just want the Textview to accept the setText method on an onclick, but when using fragments it prevents me from doing so.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_main, container, false);
    View v2 = inflater.inflate(R.layout.flash_fragment, container, false);

    Button reply = (Button) v2.findViewById(R.id.replyB);

    TextView flashtext = (TextView) v2.findViewById(R.id.flashtext);

    flashtext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //start playing the string word by word
            //on the textview : flashtext
            ***flashtext.setText("test");***
        }
    });
jakeinmn
  • 167
  • 1
  • 3
  • 13
  • I've always just made a copy of the variable within the inner class that is final, if the original can't be final for your code. – Cody Harness Oct 23 '15 at 20:44
  • I cant seem to set the variable to be final since the LayoutInflator variable is being sent into the onCreateView method and I can't set inflater to be final. – jakeinmn Oct 23 '15 at 20:47
  • What about using v, or maybe "this"? v is the View that was passed in the onClick, and I think "this" would be the button as well. – Cody Harness Oct 23 '15 at 20:50
  • Just declare `flashText` as `final`. Inside the OnClick `this` is the listener itself. If you use `v`, it would need to be casted as a TextView, then you can call `setText`, – OneCricketeer Oct 23 '15 at 20:56
  • Also, `final` means the variable assignment is unchangeable, not the object itself. – OneCricketeer Oct 23 '15 at 20:58

1 Answers1

1

I don't understand why it requires it to be set to a final, unchangeable variable

Because flashtext goes out of scope as soon as onCreateView() returns. It is a local variable, so that reference lives only for the duration of the onCreateView() call.

If you wish to use flashtext just from that listener, using final is simplest approach.

If you wish to use flashtext elsewhere in this fragment, make flashtext be a field on your Fragment subclass.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491