Home > OS >  how to create class of findViewById?
how to create class of findViewById?

Time:09-11

I am a beginner ,https://i.stack.imgur.com/k8z9T.jpgin the android studio whenever I try to use findViewById.It shows an error and they ask me to create its variable but I don't know how to create it . Please tell me, I am stuck here.

CodePudding user response:

You just created a function outside of your MainActivity. You have to create it inside of your activity. According to your screenshot, you just try to create a Top-level Function not a Function because it's outside of your activity. When you need to create a Function you have to create that inside your activity. Keep your eyes on Curley Brackets {}.

See the explanation to understand.

  • In your screenshot
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
} /* Your activity end's on here*/

private fun addNickName(view: View) {
    // Your instance
    // val editText = findViewById<EditText>(R.id.nickName_edit)
}
  • So the answer is
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    private fun addNickName(view: View) {
        // Your instance
        // val editText = findViewById<EditText>(R.id.nickName_edit)
    }
} /* Your activity end's on here*/

Hope you understand!. Thank you

  • Related