Here is my kotlin/android activity:
import kotlinx.android.synthetic.main.activity_player_details.*
class PlayerDetails : AppCompatActivity(), View.OnClickListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_player_details)
val intent = getIntent()
val numOfPlayers = intent.getIntExtra("number_of_players", 1)
next_details.setOnClickListener(this)
}
override fun onClick(v: View?) {
for (player in 1..numOfPlayers) {
// body in here
}
}
}
I want to pass the value of numOfPlayers to my onClick method so I can use it - how can I achieve this?
Either make numOfPlayer as global variable or create separate function to call when btn is clicked and pass numOfPlayer as parameter
1. make numOfPlayer as global variable
class PlayerDetails : AppCompatActivity(), View.OnClickListener {
var numOfPlayers = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_player_details)
val intent = getIntent()
numOfPlayers = intent.getIntExtra("number_of_players", 1)
next_details.setOnClickListener(this)
}
override fun onClick(v: View?) {
for (player in 1..numOfPlayers) {
// body in here
}
}
}
2. create separate function to call when btn is clicked and pass numOfPlayer as parameter
class PlayerDetails : AppCompatActivity(), View.OnClickListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_player_details)
val intent = getIntent()
val numOfPlayers = intent.getIntExtra("number_of_players", 1)
bottomNav.setOnClickListener {
onNextClick(numOfPlayers)
}
}
private fun onNextClick(numOfPlayers: Int) {
for (player in 1..numOfPlayers) {
// body in here
}
}
}
Define your variable with global scope like below
var numOfPlayers = 0
Make sure to define it above onCreate() method.
onCreate is called when the activity is created, and onClick is called when the next_details button is clicked, which definitely happens after onCreate.
So make numOfPlayers a class member and assign the value to it in onCreate, and also add the lateinit keyword to numOfPlayers so you don't need to make it nullable.
The code should look like this:
import kotlinx.android.synthetic.main.activity_player_details.*
class PlayerDetails : AppCompatActivity(), View.OnClickListener {
lateinit var numOfPlayers: Integer
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_player_details)
val intent = getIntent()
numOfPlayers = intent.getIntExtra("number_of_players", 1)
next_details.setOnClickListener(this)
}
override fun onClick(v: View?) {
for (player in 1..numOfPlayers) {
// body in here
}
}
}
Make numOfPlayers global
var numOfPlayers =0
In onCreate()
val intent = getIntent()
numOfPlayers = intent.getIntExtra("number_of_players", 1)
In onClick()
for (i in 1..numOfPlayers) {
// body in here
}
Related
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val navigate = Intent(this,Activity2::class.java)
startActivity(navigate)
}
}
}
fun switchActivity(){
val navigate = Intent(this,Activity2::class.java)
startActivity(navigate)
}
I want to start an activity from a function and not from the main activity..
I can start an activity from main class but in function, the code doesnt work..
Please help.. I'm new to kotlin android programming..
You can also try like this
class MainActivity : AppCompatActivity() {
#SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
nextActivity(this, MainActivity2())
}
private fun nextActivity(context: Context, activity: Activity) {
startActivity(Intent(context, activity::class.java))
}
}
Just use it
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
switchActivity()
}
}
fun switchActivity(){
val navigate = Intent(this#MainActivity, Activity2::class.java)
startActivity(navigate)
}
Actually i don't get your question clearly. But i'll try to answer your question based on my understanding of yours.
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
switchActivity()
// if you want to pass the class through the paramater,
// can try this
// TODO: Another Way
// switchActivityCustom(Activity2::class.java)
}
}
fun switchActivity(){
val navigate = Intent(this, Activity2::class.java)
startActivity(navigate)
}
// TODO: Another Function
// fun switchActivityCustom(destination: Class<*>,){
// val navigate = Intent(this, destination)
// startActivity(navigate)
// }
}
And the last one is, put your function inside the class (in this case: MainActivity Class)
If your function is declared at the top level, without a reference to this, you'd need to pass an instance of Activity to your function:
fun switchActivity(activity: Activity) {
val navigate = Intent(activity, Activity2::class.java)
activity.startActivity(navigate)
}
what to do so?
I declared the val here, so that i can use the val e11 in all the function but it get crashes and why?
//val e11=findViewById<EditText>(R.id.e1)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_lifecycle)
val b11=findViewById<Button>(R.id.b1)
b11.setOnClickListener{
startActivity(Intent(this,another::class.java))
}}
override fun onStart() {
super.onStart()
Toast.makeText(this, "am started", Toast.LENGTH_SHORT).show()
}override fun onResume() {
super.onResume()
Toast.makeText(this, "am resumed", Toast.LENGTH_SHORT).show()
}
override fun onPause() {
super.onPause()
val e1=findViewById<EditText>(R.id.e1)
e1.setText("")
}
}```
Try this
private val e11 : EditText by lazy { findViewById<EditText>(R.id.e1) }
As #Kishan Maurya stated out in the comments, you are trying to find a view before the view gets created in your onCreate function. A solution could be to declare e11 globally and initiate it in your onCreate like it is most common. Or you try out #Kishan Maurya's answer.
lateinit var e11 : EditText // declare var e11 globally
// lateint is a keyword to tell that this var will be initialized later
// you need a var instead of val, because e11 should not be final
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
e11 = findViewById<EditText>(R.id.e11)
// you could also initialize like below; is simple and has better readability
// e11 = findViewById(R.id.e11) as EditText
}
I have this class in a file named MainActivity.kt:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
binding.fab.setOnClickListener {
}
setContentView(binding.root)
}
override fun onResume() {
super.onResume()
fetchData()
displayBudget()
}
private fun fetchData() {
//how to use binding here? for example: binding.tvTotal.setText("0")
}
}
As you can see, I use view binding feature on Android Studio to replace findViewById. How to use binding object (val binding) in fetchData function?
By trial & error, I can use Kotlin's lateinit variable for binding object.
class MainActivity : AppCompatActivity() {
//declare the binding object here
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//initialize the binding object here
binding = ActivityMainBinding.inflate(layoutInflater)
binding.fab.setOnClickListener {
}
setContentView(binding.root)
}
override fun onResume() {
super.onResume()
fetchData()
displayBudget()
}
private fun fetchData() {
//I can use binding object here
binding.tvTotal.setText("0")
}
}
you need to initialize binding as an optional var for the entire class and then set it in the onCreate function and that will allow you to use it on the onResume without a problem
here's how to do it
class MainActivity : AppCompatActivity() {
//what the below does is create a nullable object binding of type ActivityMainBinding
var binding: ActivityMainBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
binding?.fab.setOnClickListener {
}
setContentView(binding.root)
}
override fun onResume() {
super.onResume()
fetchData()
displayBudget()
}
private fun fetchData() {
//you can now access the binding var here by using the ? operator
binding?.tvTotal.setText("0")
}
}
Try this
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.fab.setOnClickListener {
}
}
}
when a item is pressed I want to modify a value declared outside the onCreate method. But when the item is pressed, the onTouchListener does the other functions except modify that value. I've tried to write the same instruction to modify the value outside the onTouchListener method and it worked. This is my code:
class MainActivity : AppCompatActivity() {
var ciao: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var listenerUser = View.OnTouchListener(function = { view, motionEvent ->
if (motionEvent.action == MotionEvent.ACTION_DOWN) {
this.ciao = "ciao"
}
true
})
}
override fun onResume() {
super.onResume()
if (ciao != null) {
println(ciao!!)
}
}
}
When my application resumes the var ciao is null, but if I put this.ciao = "ciao" outside the listener the var isn't null.
You need to set your OnTouchListener for the view that should react:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val listener = View.OnTouchListener(function = {view, motionEvent ->
if (motionEvent.action == MotionEvent.ACTION_DOWN) {
this.ciao = "ciao"
}
true
})
clickedView.setOnTouchListener(listener)
}
If you just want to detect a click you are probably better off using a OnClickListener like this:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
clickedView.setOnClickListener(_ ->
this.ciao = "ciao"
)
}
How to convert a string to EditText , i make a EditText in one activity and then make a second activity and i get this edittext through the intent in the string then
how to assign it to the second activity's edittext , but i don't find it how to assign string to edittext.Here i used a go function that is used when onclick event is occured of button
This is my first activity
class MainActivity : AppCompatActivity() , View.OnClickListener{
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun go(v:View){
val intent=Intent(this#MainActivity,Main2Activity::class.java)
var aa=EditText1.text
intent.putExtra("name",aa)
startActivity(intent)
}
}
This is my second activity
class Main2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
var str=intent.getStringExtra("name").toString()
et21.setText(str)
}
}
In your first activity change go function as below,
fun go(v:View){
val intent=Intent(this#MainActivity,Main2Activity::class.java)
var aa=EditText1.text.toString()
intent.putExtra("name",aa)
startActivity(intent)
}
In your second activity change the last line of onCreate as below, you need to unwrap the value from an nullable type. Which can be done using let block over nullable type. Also I am assuming et21 is reference to the edit text and is properly initialised.
This solution is null safe
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
intent.getStringExtra("name")?.let {
et21.setText(it)
}
}
Its because you was trying to set charSequence to your EditText , just convert to String while getting value from FirstEditText.
inside your Second Activity -
class Main2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
intent.getStringExtra("name")?.let {
et21.setText(it)
}
}
}
Inside your first activity
fun go(v:View){
val intent=Intent(this#MainActivity,Main2Activity::class.java)
var aa=EditText1.text.toString()
intent.putExtra("name",aa)
startActivity(intent)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
val extras:Bundle =intent.extras
val nn=extras.getString("name")
eT21.setText("${nn}")
}
Or
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
eT21.setText(intent.getStringExtra("name"))
}