Problems with TextView in Android Studio 3.0.1

1

Hello, I am using Android Studio 3.0.1 and the TextView marks it on red as an error, says

  

Function invocation 'TextView (...)' expected None of the following   functions can be called with the arguments supplied. (Context!)   defined in android.widget.TextView (Context !, AttributeSet!)   defined in android.widget.TextView (Context !, AttributeSet !,   Int) defined in android.widget.TextView (Context!   AttributeSet !, Int, Int) defined in android.widget.TextVie

The operator = brand

  

Expecting an element

And calling the variable myText to implement the setText () method marks

  

Unresolved reference: miText



Here is the MainActivity.kt code

package holamundo.programming.app.tuto.com.myapplication

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main);

        TextView miTexto = (TextView)findViewById(R.id.textView);

        miTexto.setText("He cambiado");

    }
}

I really saw several videos and I read in several pages but they all do the same thing and it does not work for me, it will be the IDE version ??

    
asked by Electrisik Vocal 08.03.2018 в 04:39
source

2 answers

0

The problem is that you are using Kotlin and not Java , in this case you should get the reference of TextView in this way:

 val miTexto: TextView  = findViewById<TextView>(R.id.textView) as TextView
 miTexto.text = "He cambiado"

Your project was created with support Kotlin so you must program in Kotlin :)

    
answered by 08.03.2018 / 18:36
source
0

You are using Kotlin in your project, therefore it is not necessary to cast the element you are referring to.

If for example in your activity in the XML you have a widget like the following:

<TextView
        android:id="@+id/texto_modificar"
        tools:text="Mi Texto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

and you want to modify the text, you can do it without having to do the cast that is done in java, simply by calling the id you can access all the properties of that widget or element.

to change the text, if for example you have a variable in your file kt and you want to pass it to your widget you can do it in the following way:

val miVariable = "Hola"

texto_modificar.text = miVariable  // opcion con variable
texto_modificar.text = "aqui va tu nuevo texto"   // opcion donde escribes directamente el texto

Remember that it is also better to handle all the strings that are assigned directly to the views from the strings.xml file found in the /res/values/ directory of your project.

    
answered by 20.03.2018 в 17:49