I am new to Kotlin and android development.
I have a MainActivity.kt file, its associated activitymain.xml file, and a card_layout xml layout file. I would like to be able to access a view from the card_layout.xml in MainActivity.kt, but whenever I try to access the view I get a null pointer exception.
I try to access the view like so in OnCreate() of MainActivity.kt:
val v = findViewById<RelativeLayout>(R.id.rv_relative_layout)
and get this error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{...MainActivity}: java.lang.NullPointerException: onCreate$lambda-1(...) must not be null
Does anyone know why this occurs, and have a way for properly accessing Views from other xml files?
CodePudding user response:
Don't know if this will be specifically useful...New too. I find two ways of referencing views most effective.
- ViewBinding :
inside
build.gradle (Module:App_Name.app)
android {
...
buildFeatures{
viewBinding = true
}
}
in MainActivity:
class HistoryActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
Then reference your veiws by typing binding.camelCaseViewName eg. binding.rvRelativeLayout
- first create the view variable as a lateinit var before onCreate then instantiate in the place you need it.
im not sure I have understood your question correctly though. My answer is about accessing from .kt not from other xml files.
CodePudding user response:
It will return null because the default findViewById
method of the current Activity
is only using the assign Views
from the setLayout
method.
You need to inflate another layout so you can access its Views
from your Activity
by using LayoutInflater's inflate
method.
val view = layoutInflater.inflate(R.layout.other_layout, null)
val viewFromOther = view.findViewById<View>(R.id.view_from_other)