1

So I would like to create a new TextView when a button is clicked. For some reason, TextView(this) doesn't work when it is inside of an onClick(). I would like to be able to do this with just java.

Again, when I create a TextView inside of onClick, there is an error when I make a TextView(this).

EditText name = layout.findViewById(R.id.enterName);
        final String Name = name.getText().toString();
        Button create = layout.findViewById(R.id.create);
        create.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView textView = new TextView(this);
                textView.setText(Name);
            }
        });

I get the error, "TextView (android.content.Context) in TextView cannot be applied to (anonymous android.view.View.OnClickListener)".

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
  • Check my answer here : https://stackoverflow.com/questions/56499763/unable-to-display-textview-on-button-click-in-android/56500040#56500040 – Vinay Hegde Jun 07 '19 at 19:32

4 Answers4

0

this in the context of the inner class points to the instance of the inner class, which is not (as the error says) a Context (it's an event listener). If you want to use the outer class instance, you have to prefix the this with a class qualifier, i.e. MyClass.this, where MyClass is the name of the class you are calling this code from.

Piotr Wilkin
  • 3,446
  • 10
  • 18
0

When you are inside of the click listener this refers to the listener, not the activity. You need to instantiate the TextView with a reference to the activity or context instead.

bmcglynn
  • 165
  • 1
  • 6
0

Try to replace this line:

  TextView textView = new TextView(this);

With this line:

TextView textView = new TextView(Activity.this);

You need to use your Activity.this if you want to pass the context.

this refers to the inner class (OnClickListener) and not to your Activity (your outer class)

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
0

Your code is Ok, the only problem is that you are creating a textview but not adding it to the layout.

So add

layout.addView(textView);

below

textView.setText(Name);
Davi
  • 1,031
  • 12
  • 21