Why .text only works inside onCreate ? At least at my code : - android

I am learning android studio and I can't find out why it happens, I would appreciate if someone could explain me this:
When I place xxxxanything.text after the onCreate I get the error " expected member declaration" but it works inside the onCreate metod.Why does it happen ?
I saw activity life cycle some times but im still in doubt about where to put things, like onclick listener.
I were wondering at several guides already and I am working on udacity at moment, having a hard time to understand recyclerview and I also trying to develop good programing practices.
I really appreciate any help you can provide.
Works like this
package app.helloworld.dashimir.com.diceroller
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val rollButton: Button = findViewById(R.id.roll_button)
rollButton.text = "Let's Roll"
}
}
but i get error when i place it after on create : expected member declaration;
package app.helloworld.dashimir.com.diceroller
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
val rollButton: Button = findViewById(R.id.roll_button)
rollButton.text = "Let's Roll"
}

In kotlin (.kt) files your code should be inside a function (normally main). In Android development this means that usually your code will be inside methods like the onCreate from an activity, but other methods from classes or top level functions (outside of a class) work as well.
In your example the code you moved outside the onCreate includes a value declaration val rollButton: Button = findViewById(R.id.roll_button) which is valid inside the body of a class since it will be turned into a property of said class. But the second line: rollButton.text = "Let's Roll" is an assignment an those can only be performed inside a function.
Additionally, in Android with kotlin you have available kotlin android extensions which let you reference views from the xml directly using their id without the need of using findViewById

One of best ways it build out function.
first: add OnClick to button in xml file:
android:OnClick="OnClick"
second: build Onclick function in MainActivity class and don't forget the constructor (v:View):
package app.helloworld.dashimir.com.diceroller
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun OnClick(v:View){
val rollButton: Button = findViewById(R.id.roll_button)
rollButton.text = "Let's Roll"
}

Related

Kotlin: Unresolved reference: Textview

I am new to Kotlin and android in general.
Currently making an app that is supposed to calculate a persons age in minutes, however Im getting an error saying "Unresolved reference: TextView". The thing is, as you can see, I've already imported widget.Textview.
Please help... I'm stuck on such a trivial problem. Thank you.
P.S. There have been similar questions, but the solutions either aren't applicable or have already been applied.
import android.app.DatePickerDialog
import android.content.ReceiverCallNotAllowedException
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import android.widget.Button
import android.widget.Toast
import java.util.*
class MainActivity : AppCompatActivity() {
private var tvSelectedDate : Textview? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btndate : Button = findViewById(R.id.btndate)
tvSelectedDate = findViewById(R.id.tvSelectedDate)
btndate.setOnClickListener {
clickDatePicker()
}
}
...
I believe this is a simple typo:
private var tvSelectedDate : Textview? = null
You have written Textview, but should have written TextView (with a captial "V").
Simply using databinding to get view id and handle alot of issues
Data binding

Why can't I access a component from my xml file by declaring an object globally?

So here is the code in my MainActivity.kt file
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)}
var tvInput: TextView = findViewById(R.id.tvInput)
fun onDigit(view: View){
tvInput.append((view as Button).text)
}
fun onClear(view: View){
tvInput.text = ""
}
}
When I declare the object "tvInput" globally like I have done above, it keeps crashing the app, however when I declare it separately for each function it runs smoothly, How can I fix this?
findViewById() searches the current layout for the view and throws an exception if it isn't found. But there is no current layout yet at the time the Activity class is instantiated. There is only a layout after you have called setContentView() in the onCreate() function. Your tvInput property in your example is calling findViewById() at the time the class is instantiated.
If you want to delay when it first calls findViewById(), you can use a Lazy delegate like this, and it will resolve the issue:
val tvInput: TextView by lazy { findViewById(R.id.tvInput) }
Now it won't call findViewById() until the first time you actually use the property, which will happen after you call setContentView().
Declare tvInput globally by lateinit.
Initialise tvImput in onCreate method then use in other functions.

How do I fix these 5 Android SDK compilation errors?

I am following this viewflipper tutorial. After the build I am receiving the following errors:
Unresolved reference: activity_main
Unresolved reference: view_flipper
Smart cast to 'ViewFlipper!' is impossible, because 'viewFlipper' is a mutable property that could have been changed by this time
Smart cast to 'ViewFlipper!' is impossible, because 'viewFlipper' is a mutable property that could have been changed by this time
Smart cast to 'ViewFlipper!' is impossible, because 'viewFlipper' is a mutable property that could have been changed by this time
Listed below is the code to my MainActivity.kt
'''
package com.example.mobilecop
import android.R
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.TextView
import android.widget.ViewFlipper
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private var viewFlipper: ViewFlipper? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewFlipper = findViewById(R.id.view_flipper)
val textView = TextView(this)
textView.text = "Dynamically added TextView"
textView.gravity = Gravity.CENTER
viewFlipper.addView(textView)
viewFlipper.setFlipInterval(2000)
viewFlipper.startFlipping()
}
fun previousView(v: View?) {
viewFlipper!!.setInAnimation(this, R.anim.slide_out_right)
viewFlipper!!.setOutAnimation(this, R.anim.slide_in_left)
viewFlipper!!.showPrevious()
}
fun nextView(v: View?) {
viewFlipper!!.setInAnimation(this, R.anim.slide_in_left)
viewFlipper!!.setOutAnimation(this, R.anim.slide_out_right)
viewFlipper!!.showNext()
}
}
'''
After removing import android. R, I was able to fix the first two errors. I removed the following three lines and the app runs.
'''viewFlipper.addView(textView)
viewFlipper.setFlipInterval(2000)
viewFlipper.startFlipping()
'''

Need some suggestion for keyboard hiding code

I always found one problem whenever i make forms (for example, login or registration form) in my applications, that problem is hiding keyboard when user clicks on submit button. For solving this problem i always write keyboard hiding code in the very 1st line in the click listener, this solution was fine if i've only 1 or 2 forms in my app, but if there are saveral forms in an app than it becomes a certain overhead on the actual business logic of the app. Taking this overhead of maintaining 'keyboard visibility' in mind i've developed a generic solution to handle this problem. I am learning to develop android app using kotlin and by using 'default methods' of interface of kotlin i've developed this code.
I am sharing the code with you and i need your suggestions and
improvements on this approach.
I want to know whether i can use this approach in my live projects or
i just can't use this approach because this is wrong. Please give me
your valuable feedback.
MainActivity :
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity(), CustomOnClickListener {
override fun onClick(v: View?) {
super<CustomOnClickListener>.onClick(v)
when(v?.id){
R.id.button1 -> Toast.makeText(this, "button1 clicked", Toast.LENGTH_LONG).show()
R.id.button2 -> Toast.makeText(this, "button2 clicked", Toast.LENGTH_LONG).show()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button1.setOnClickListener(this)
button2.setOnClickListener(this)
}
}
CustomOnClickListener
import android.app.Activity
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
interface CustomOnClickListener : View.OnClickListener{
override fun onClick(v: View?) {
v?.hideKeyboard()
}
}
fun View.hideKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
}

Kotlin Navigation - Back Button not working

I have the following code in Kotlin
package com.example.android.navigation
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.navigation.findNavController
import androidx.navigation.ui.NavigationUI
import com.example.android.navigation.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
val navcon = this.findNavController(R.id.NavFragment)
NavigationUI.setupActionBarWithNavController(this, navcon)
}
override fun onNavigateUp(): Boolean {
val navcon = this.findNavController(R.id.NavFragment)
return navcon.navigateUp()
}
}
The code is supposed to implement the back button and make it work correctly (navigate up the back stack). However, when I run the application and click on the generated back button, nothing happens (the button doesn't work, but also no error is produced when clicked). Does anyone have any idea as to why it doesn't work / how to make it work properly?
AppCompatActivity has a separate onSupportNavigateUp() method, which should be used instead of onNavigateUp() as per the Navigation Action Bar documentation.

Categories

Resources