I am new to Android Studio. I wrote a simple code in the main_activity.xml file, with ids. But when I try to reference the ids from my MainActivity.kt file. It shows an error Unresolved reference: btnDatePicker i.e an unresolved error.
I don't know what wrong. Here's a screenshot of my MainActivity.kt file. As you can see, when I try to call the id btnDatePicker, it returns an error.
And Here's a screenshot of my activity_main.xml, as you'll see I have circled the particular id I'm trying to reference.
Id cannot be referenced directly
Under normal conditions, you can bind the control using the following code:
val button = findViewById<Button>(R.id.btnDatePicker)
and if you want to use id directly, i think this article can help you
View Binding
Just try to rebuild project,Build -> Rebuild project
We have 2 variant and I recommend it. I recommend you use View Binding. Because Koltin synthetic(just writing id element) is deprecated.
To enable view binding in a module, set the viewBinding build option to true in the module-level build.gradle file, as shown in the following example:
android {
...
buildFeatures {
viewBinding = true
}
}
Usage
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding(layoutInflater)
val view = binding.root
setContentView(view)
}
then use your xml elements
binding.btnDataPicker.setOnClickListener {
...
}
Just add this in your gradle file in plugins id 'kotlin-android-extensions'
plugins {
id 'kotlin-android-extensions'
}
Just add this in your gradle file in plugins id 'kotlin-android-extensions'
Related
I am trying to use the documentation example provided in the reference
https://developer.android.com/training/keyboard-input/commands
for implementing the onKeyUp override function. In simplified form this is
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
when (keyCode) {
KeyEvent.KEYCODE_SYSTEM_NAVIGATION_DOWN -> {
// do stuff here
return true
}
else -> super.onKeyUp(keyCode,event)
}
}// end override fun onKeyUp
the problem is that Android Studio doesn't recognize the super.onKeyUp function. Apparently I haven't established the input source correctly as the override isn't recognized either. I can get the result I want, sort of, by starting the class as follows
class KeyboardController(view: View, fragmentActivity: FragmentActivity) : InputController(),
View.OnKeyListener {// start class KeyboardController
then creating the override function
override fun onKey(v: View?, keyCode: Int, event: KeyEvent?): Boolean {
and then checking event.action and testing the key up and down keycodes individually but I seem to be missing something basic in order to use the example code above. Additionally the documentation at https://developer.android.com/guide/topics/ui/ui-events
indicates that View.OnKeyListener class supports the onKeyUp function but as indicated above android studio doesn't recognize the onKeyUp function so I cannot override it. What am I missing or is the documentation wrong?
I am using Android Studio Chipmunk (2021.2.1) with Kotlin.
Any feedback appreciated.
I have kotlin project where I'm using Jaxb generated src files from xsd. The problem with these generated sources is that they have nullable fields but IDEA does not know about it. It can lead to bugs in production. To fix it we can add #Nullable annotation to all getters in generated srs-es.
How can we do it gracefully?
I made this solution, it works for me but maybe somebody knows better approuch?
Gradle kt task
tasks.register("nullableForXsdFields") {
group = "code generation"
description = "Add Nullable annotation to generated jaxb files"
actions.add {
val xjcFiles = fileTree("$buildDir/generated-sources/main/xjc")
xjcFiles.forEach { xjcFile ->
var content = xjcFile.readText()
Regex("(public) (\\w+|<|>|\\*) (get)").findAll(content).distinct()
.forEach { match ->
content = content.replace(
match.groups[0]!!.value,
match.groups[0]!!.value.replace("public ", "public #Nullable ")
)
}.run {
content = content.replace(
"import javax.xml.bind.annotation.XmlType;",
"import javax.xml.bind.annotation.XmlType;\nimport org.jetbrains.annotations.Nullable;"
)
}
xjcFile.writeBytes(content.toByteArray())
}
}
}
tasks.getByName("xjcGeneration").finalizedBy("nullableForXsdFields")
tasks.getByName("compileKotlin").dependsOn("nullableForXsdFields")
tasks.getByName("compileJava").dependsOn("nullableForXsdFields")
xjcGeneration - is my plugin to generate src from xsd
I faced the same problem, so I've created an extension for maven jaxb plugin
com.github.labai:labai-jsr305-jaxb-plugin.
This extension marks all generated packages as nullable by default, and then marks with #NotNull only those fields, which are mandatory by xsd scheme.
You can find more details how to use it with maven in github
https://github.com/labai/labai-jsr305
when I try to directly type the button id in main activity of kotlin , it does not pick it up automatically, instead it says unresolved reference, what is wrong with Android Studio??
In my case I had the same problem and have solved it this way with Android Studio 4.x:
Put this in your apps build.gradle or build.gradle.kts. The latter in my case because my project is made with Kotlin KMM.
buildFeatures {
viewBinding = true
}
Here is my complete build.gradle.kts so you can see where it belongs to:
plugins {
id("com.android.application")
kotlin("android")
id("androidx.navigation.safeargs.kotlin")
}
dependencies {
implementation(project(":shared"))
implementation("com.google.android.material:material:1.3.0")
implementation("androidx.appcompat:appcompat:1.2.0")
implementation("androidx.constraintlayout:constraintlayout:2.0.4")
implementation("androidx.navigation:navigation-fragment-ktx:2.3.4")
implementation("androidx.navigation:navigation-ui-ktx:2.3.4")
}
android {
compileSdkVersion(30)
defaultConfig {
applicationId = "************************"
minSdkVersion(24)
targetSdkVersion(30)
versionCode = 1
versionName = "1.0"
}
buildTypes {
getByName("release") {
isMinifyEnabled = false
}
}
buildFeatures {
viewBinding = true
}
}
Here you can read all about it. Also if you are using Android Studio lower than 4.x how it has to be done.
https://developer.android.com/topic/libraries/view-binding
Don't forget to sync your project. It will only appear after that step. You can check it by having a look at dataBinding folder which you will find at that path.
build > generated > data_binding_base_class_source_out > debug > out > rest is app specific
and the last folder will be "dataBinding" folder.
Have fun!
It's hard to advise anything without being given any code.
I'm guessing you're using Kotlin synthetic import? Then you would also need to import something like this import kotlinx.android.synthetic.main.activity_main.* to be able to use view elements without findById. Also, make su you have integrated Kotlin extensions plugin.
Also, I can't rule out this possibility, since I can't see any of your code, but maybe check if the view element you're trying to access in MainActivity is in it's layout?
I have a view using core data and xcdatamodeld file that contains the definition for an Item struct. If I use Xcode to generate the files for Item and manually manage them, preview works fine. However, when I use Codegen in either of the other formations, I get errors saying that the entire struct is undefined. This prevents the previews from working.
Code:
struct ArchiveView: View {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
#FetchRequest(entity: Item.entity(), sortDescriptors: []) var fetchedResults: FetchedResults<Item>
var body: some View {
return NavigationView {
List(fetchedResults, id: \.self ) { (fetchedResult: Item) in
return PurchaseView(name: fetchedResults.name price: fetchedResults.price, purchaseDate: fetchedResults.date)
}
}.navigationBarTitle("Order")
}
}
Both the Item+CoreDataClass and Item+CoreDataProperties are missing since they are automatically generated by xcode.
I am now using manual Codegen to be able to see the previews, but am curious whether I could use the other options. How can I use Class Defintion Codegen for the core data files and still be able to use SwiftUI previews?
After some testing, something appears to be wrong with the xcode code generator itself. Whenever I change the code generator to anything other than Class Definition at least once, this breaks the linking with previews.
The fix was to create a new project and copy over the old files.
I have a parent gradle script with some common configuration, but I need to override some values. For this values I define extra properties. Next, in a project I apply the parent file, but I'm not able to override the the value. Here is what I try to do, but id doesn't work.
Parent gradle script (parent.gradle)
apply plugin: 'maven'
ext {
artifact = "test"
}
uploadArchives {
repositories.mavenDeployer {
repository(url: 'someUrl') {
authentication(userName: 'username', password: 'password')
}
pom.project {
artifactId artifact
}
}
}
Project gradle script (build.gradle)
apply from: 'parent.gradle'
ext {
artifact = "parent-gradle"
}
...
In the documentation I did not find any reference on how to do this.
Any idea on how I can do this?
Thanks Peter. Moving the ext statement before apply in the build.gradle, and removing it from parent.gradle solved my problem.