folks. I have been working on a project with kotlin and I need to make a fragment that comunicate with the parent activity... I followed exactly what google and other websites suggested but I still get an error "activity does not override anything"... All of the other solutions are not working for me... here is the code .
FRAGMENT
package com.me.assistan.assistant
import android.app.Activity
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.Context
import android.content.Intent
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CompoundButton
import android.widget.LinearLayout
import android.widget.ToggleButton
import kotlinx.android.synthetic.main.content_newplan.*
import java.util.*
class addingTask : Fragment(), View.OnClickListener{
var func = Functions
var globalTask = GlobalTask
private lateinit var listener: OnTimeSettedListener
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is OnTimeSettedListener) {
listener = context
} else {
throw ClassCastException(context!!.toString() + " must implement
OnTimeSettedListener.")
}
}
companion object {
fun newInstance(): addingTask {
return addingTask()
}
}
override fun onCreateView(inflater: LayoutInflater?, container:
ViewGroup?,
savedInstanceState: Bundle?): View? {
val view: View = inflater!!.inflate(R.layout.fragment_adding_task,
container,
false)
val activity = activity
view.theTime.setOnClickListener { v ->
listener.onTimeSetListtedener("test")
}
return view
}
interface OnTimeSettedListener{
fun onTimeSetListtedener(comic : String){
println("ok")
}
}
}// Required empty public constructor
And not the MAIN ACTIVITY
class Newplan : AppCompatActivity(), addingTask.OnTimeSettedListener {
var posx = 0f
private var startx = 0f
private var posy = 0f
private var starty = 0f
var backIntent = Intent();
var func = Functions
var globalTask = GlobalTask
val fragment = addingTask()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_newplan)
if(savedInstanceState === null){
var args = Bundle()
supportFragmentManager.beginTransaction()
.add(R.id.taskMain, addingTask.newInstance(),"newTask")
.commit()
}
}
override fun onTimeSettedListener(comic : String){
println("params")
}
}
I get the error on the activity class... When I remove the "override?, the error is gone but nothing happen when I click on the button... What am I doing wrong?
I think you shouldn't add method body to your interface method. It is not allowed in Java. In Kotlin there is no error that showing method body is restricted. But you should remove body. Change your interface like
interface OnTimeSettedListener{
fun onTimeSetListtedener(comic : String)
}
Also actually you are not overriding your Listener's method. Method name in OnTimeSettedListener is onTimeSetListtedener but you are overriding onTimeSettedListener which is not really exist in your code.
Also as #albodelu mentioned answer and #chris mentioned in comments, you cannot write methods in methods. It is not correct usage.
As #chris commented, you need to move the lines below outside of onCreate() method:
override fun onTimeSettedListener(comic: String) {
println("params")
}
You also need to match names replacing
interface OnTimeSettedListener {
fun onTimeSetListtedener(comic : String){
println("ok")
}
}
by
interface OnTimeSettedListener {
fun onTimeSettedListener(comic: String) {
println("ok")
}
}
Update
If you fix the name typo and remove the default implementation of the onTimeSettedListener declaration in the interface inside your fragment, as your activity implements it and Android Studio warns you about the missing override, it's possible to click it and select that the IDE implements it for you to avoid errors doing it:
interface OnTimeSettedListener{
fun onTimeSettedListener(comic : String)
}
You also need to fix the call replacing:
listener.onTimeSetListtedener("test")
by
listener.onTimeSettedListener("test")
Related
My Main Activity Class
This is implemented to learn recycler view and to handle clicks. The below code works fine but while implementing listener I got confused. All the doubts are listed below. Do help.
package com.suasnom.pizzarecyclerview
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity(), isClickedInterface {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//implementing recycler view
recycler_view.layoutManager= LinearLayoutManager(this)
val data = fetchData()
val adapter = CustomAdapter(data, this)
recycler_view.adapter = adapter
}
fun fetchData(): ArrayList<String> {
val list_Strings = ArrayList<String>()
var str = ""
for(i in 1..100){
str = "${i} line"
list_Strings.add(str)
}
return list_Strings
}
override fun onItemClicked(item: String) {
Toast.makeText(this, "$item", Toast.LENGTH_LONG).show()
}
}
In this statement I passed
val adapter = CustomAdapter(data, this)
and it allows me to override the below method:
override fun onItemClicked(item: String) {
Toast.makeText(this, "$item", Toast.LENGTH_LONG).show()
}
The below code is for recycler view adapter where I write that interface:
package com.suasnom.pizzarecyclerview
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import android.view.View
import androidx.recyclerview.widget.RecyclerView
class CustomAdapter(val list_strings: ArrayList<String>, private val listner: isClickedInterface): RecyclerView.Adapter<PizzaViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PizzaViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.row, parent, false)
val pizzaObject = PizzaViewHolder(view)
view.setOnClickListener {
listner.onItemClicked(list_strings[pizzaObject.adapterPosition])
}
return pizzaObject
}
override fun onBindViewHolder(holder: PizzaViewHolder, position: Int) {
val data_incoming = list_strings[position]
holder.text_message.text = data_incoming
}
override fun getItemCount(): Int {
return list_strings.size
}
}
class PizzaViewHolder(private val view: View): RecyclerView.ViewHolder(view){
val text_message = view.findViewById<TextView>(R.id.textrow)
}
interface isClickedInterface{
fun onItemClicked(item: String){}
}
Any idea how this is working. Please Help ...
inside CustomAdapter on the bottom you have declared isClickedInterface (it might be declared anywhere else or as separated file). it is implemented by your MainActivity (after :), so you have to set this interface methods inside implementing class - so in Activity appears onItemClicked(item: String) method
now your CustomAdapter have constructor param to pass this interface (second one). for initiating new instance of adapter you have pass implemented interface, in here you may pass whole Activity as it implements desired interface (val adapter = CustomAdapter(data, this) - this points on Activity, which is also an isClickedInterface interface instance)
now inside onCreateViewHolder you are setting setOnClickListener and inside of it you are calling method from passed interface in constructor
In my app I have a MainActivity which has mobile navigation implemented with a navBar and all that stuff. When I navigate to a fragment there needs to be a Youtube Video Player inside. As I'm developing a one activity application so far I tried to implement the Fragment approach on the Youtube API.
I'm having issues with YoutubePlayerSupportFragment. I made it work following this suggestion: https://stackoverflow.com/a/58792809/13150066
But this solution is, to me, kind of shady. I'm afraid this solution will crash sometime, or will not work as the API itself would.
This is the error was having with 'android.support.v4.app.Fragment'
And as the suggestion above suggests... I created a new custom class, YoutubePlayerSupportFragmentX which extends from the Fragment class that I have no issues with, androidx.fragment.app.Fragment, and this is it's code:
YoutubePlayerSupportFragmentX.kt
package com.google.android.youtube.player //<--- IMPORTANT!!!!
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.google.android.youtube.player.internal.ab
import java.util.*
class YouTubePlayerSupportFragmentX : Fragment(), YouTubePlayer.Provider {
private val a = ViewBundle()
private var b: Bundle? = null
private var c: YouTubePlayerView? = null
private var d: String? = null
private var e: YouTubePlayer.OnInitializedListener? = null
override fun initialize(var1: String, var2: YouTubePlayer.OnInitializedListener) {
d = ab.a(var1, "Developer key cannot be null or empty")
e = var2
a()
}
private fun a() {
if (c != null && e != null) {
c?.a(this.activity, this, d, e, b)
b = null
e = null
}
}
override fun onCreate(var1: Bundle?) {
super.onCreate(var1)
b = var1?.getBundle("YouTubePlayerSupportFragment.KEY_PLAYER_VIEW_STATE")
}
override fun onCreateView(var1: LayoutInflater, var2: ViewGroup?, var3: Bundle?): android.view.View? {
c = YouTubePlayerView(Objects.requireNonNull(this.activity), null, 0, a) // and this line compiles but gives red warning
a()
return c
}
override fun onStart() {
super.onStart()
c?.a()
}
override fun onResume() {
super.onResume()
c?.b()
}
override fun onPause() {
c?.c()
super.onPause()
}
override fun onSaveInstanceState(var1: Bundle) {
super.onSaveInstanceState(var1)
(if (c != null) c?.e() else b)?.let { var2 ->
var1.putBundle("YouTubePlayerSupportFragment.KEY_PLAYER_VIEW_STATE", var2)
}
}
override fun onStop() {
c?.d()
super.onStop()
}
override fun onDestroyView() {
this.activity?.let { c?.c(it.isFinishing) }
c = null
super.onDestroyView()
}
override fun onDestroy() {
if (c != null) {
val var1 = this.activity
c?.b(var1 == null || var1.isFinishing)
}
super.onDestroy()
}
private inner class ViewBundle : YouTubePlayerView.b {
override fun a(var1: YouTubePlayerView, var2: String, var3: YouTubePlayer.OnInitializedListener) {
e?.let { initialize(var2, it) }
}
override fun a(var1: YouTubePlayerView) {}
}
companion object {
fun newInstance(): YouTubePlayerSupportFragmentX {
return YouTubePlayerSupportFragmentX()
}
}
}
And this is my fragment class in which I implement the YoutubePlayerSupportFragmentX
VideoPlayerFragment.kt
package com.vegdev.vegacademy.ui.learning
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.google.android.youtube.player.*
import com.vegdev.vegacademy.R
class VideoPlayerFragment : Fragment() {
private var link: String? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
arguments?.let {
val safeArgs = VideoPlayerFragmentArgs.fromBundle(it)
link = safeArgs.link
}
val youtubePlayerFragment = YouTubePlayerSupportFragmentX.newInstance()
val transaction = childFragmentManager.beginTransaction()
transaction.replace(R.id.player, youtubePlayerFragment).commit()
youtubePlayerFragment.initialize(resources.getString(R.string.API_KEY), object : YouTubePlayer.OnInitializedListener {
override fun onInitializationSuccess(
p0: YouTubePlayer.Provider?,
p1: YouTubePlayer?,
p2: Boolean
) {
p1?.loadVideo(link)
}
override fun onInitializationFailure(
p0: YouTubePlayer.Provider?,
p1: YouTubeInitializationResult?
) {
}
})
return inflater.inflate(R.layout.fragment_video_player, container, false)
}
}
fragment_video_player.XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blackBackground"
tools:context=".ui.learning.VideoPlayerFragment">
<FrameLayout
android:id="#+id/player"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
I tried changing dependencies, I tried erasing folder "/.idea/libraries", cleans and builds, everything I could find online. The only thing that did it was the suggestion above.
So my questions are:
Why am I getting that error with Fragment v4?
Am I implementing it wrong? Because it works just fine, except for the fullscreen but I've read that it's a common issue.
If you've implemented a Youtube Video inside a fragment, did you use another API? Is this the only one?
Put your class on a fragment directly over an activity such as:
<fragment android:name="com.google.android.youtube.player.YouTubePlayerSupportFragmentX" android:id="#+id/fragPlayer" android:layout_width="match_parent" android:layout_height="match_parent"/>
Your activity may implements YouTubePlayer.OnInitializedListener, and on your onCreate event call to object and initializate it:
val playerView : YouTubePlayerSupportFragmentX = supportFragmentManager.findFragmentById(R.id.fragPlayer) as YouTubePlayerSupportFragmentX
playerView.initialize(getString(R.string.YOUTUBE_API_KEY), this)
Remember to include your class YouTubePlayerSupportFragmentX on the com.google.android.youtube.Player.YouTubePlayerSupportFragmentX package.
In my case, I used only one API. This how it looks like:
I'm following UDACITY free course on developing Android apps with Kotlin and I'm actually at the Viewmodel/MVVM part of the lesson, ie implementing Viewmodel classes for a better separation of concerns. So anyway, Im blocked right now. The exercise I'm on is about creating the Viewmodel class and transferring variables and functions from the Fragment class to this newly created class. I follow the tutorial step by step, check the correct answer on the provided git diff and I still find myself blocked by Unresolved reference errors.
Before changing the code, i had to update my Gradle module file to use ViewModel
//ViewModel
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
Then I had to declare my Viewmodel object in my Fragment class
gameViewModel = ViewModelProviders.of(this).get(GameViewModel::class.java)
ViewModelProviders being deprecated, old course, I had to change, after search, to
gameViewModel = ViewModelProvider(this).get(GameViewModel::class.java)
It seems to be the right way to do, but I'm still left with some Unresolved references on the variables word (gameViewModel.word) and score (gameViewModel.score) in the Fragment class, unable to compile. I dont know if I declared the Viewmodel object correctly or if I'm missing something else...
I dont have this problem, Unresolved reference, with my ViewModel class functions, ie gameViewModel.onCorrect() and gameViewModel.onSkip(). They seem to be properly declared and called in the Fragment class, which begs me the question on my variables, word and score...
My Fragment class
package com.example.android.guesstheword.screens.game
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.NavHostFragment.findNavController
import com.example.android.guesstheword.R
import com.example.android.guesstheword.databinding.GameFragmentBinding
import timber.log.Timber
class GameFragment : Fragment() {
private lateinit var binding: GameFragmentBinding
private lateinit var gameViewModel: GameViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate view and obtain an instance of the binding class
binding = DataBindingUtil.inflate(
inflater,
R.layout.game_fragment,
container,
false
)
Timber.i("onCreateView GameFragment called")
gameViewModel = ViewModelProvider(this).get(GameViewModel::class.java)
Timber.i("ViewModelProvider is called")
binding.correctButton.setOnClickListener {
gameViewModel.onCorrect()
updateScoreText()
updateWordText()
}
binding.skipButton.setOnClickListener {
gameViewModel.onSkip()
updateScoreText()
updateWordText()
}
updateScoreText()
updateWordText()
return binding.root
}
/**
* Called when the game is finished
*/
fun gameFinished() {
val action = GameFragmentDirections.actionGameToScore(gameViewModel.score)
findNavController(this).navigate(action)
}
/** Methods for updating the UI **/
private fun updateWordText() {
binding.wordText.text = gameViewModel.word
}
private fun updateScoreText() {
binding.scoreText.text = gameViewModel.score.toString()
}
override fun onDestroyView() {
super.onDestroyView()
Timber.i("onDestroyView GameFragment called")
}
}
My ViewModel class
package com.example.android.guesstheword.screens.game
import androidx.lifecycle.ViewModel
import timber.log.Timber
var word = ""
var score = 0
private lateinit var wordList: MutableList<String>
class GameViewModel: ViewModel() {
init {
Timber.i("GameViewModel is created")
resetList()
nextWord()
}
override fun onCleared() {
super.onCleared()
Timber.i("GameViewModel is cleared")
}
/**
* Resets the list of words and randomizes the order
*/
fun resetList() {
wordList = mutableListOf(
"queen",
"hospital",
"basketball",
"cat",
"change",
"snail",
"soup",
"calendar",
"sad",
"desk",
"guitar",
"home",
"railway",
"zebra",
"jelly",
"car",
"crow",
"trade",
"bag",
"roll",
"bubble"
)
wordList.shuffle()
}
/**
* Moves to the next word in the list
*/
private fun nextWord() {
//Select and remove a word from the list
if (wordList.isEmpty()) {
//gameFinished()
} else {
word = wordList.removeAt(0)
}
}
/** Methods for buttons presses **/
fun onSkip() {
score--
nextWord()
}
fun onCorrect() {
score++
nextWord()
}
}
Where did I screw up ?
The variables you're trying to access aren't part of the same scope:
var word = ""
var score = 0
private lateinit var wordList: MutableList<String>
class GameViewModel: ViewModel() {
...
your variables are declared outside of the ViewModel, add them inside the class GameViewModel to make them instance variables:
class GameViewModel: ViewModel() {
var word = ""
var score = 0
...
}
in the below code, i have 2 fragments FragmentLeft and FragmentRight both extends from Fragment class.
according to the extenstion methods below, i am trying to use a generic data type as a parameter to the method, so that when i use this method it should accept either instances of FragmentLeft or FragmentRight.....
however, the code below generates an error stated in the comment
please let me know how to solve it
code
var fragTransactionInstance = getFragmentManagerInstance()?.let {
it.getFragmentTransactionInstance()
?.replaceTransaction(R.id.fragLeft, fragmentLeft)//no enough
information to infer type variable T
?.replaceTransaction(R.id.fragRight, fragmentRight)////no
enough information to infer type variable T
}?.also {
it.commit()
}
}
fun initViews() : Unit {
fragmentLeft = FragmentLeft()
fragmentRight = FragmentRight()
}
fun <T : Fragment> FragmentTransaction.replaceTransaction(layout: Int, t:
Fragment?): FragmentTransaction {
return this.replace(layout, t)
}
classes:
import android.os.Bundle
import android.support.v4.app.Fragment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.kotlindynmaicfragment_v1.MainActivity
import com.example.kotlindynmaicfragment_v1.R
import kotlinx.android.synthetic.main.activity_main.view.*
class FragmentRight : Fragment() {
val LOG_TAG = this::class.java.name
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(LOG_TAG, "onCreate")
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
Log.d(LOG_TAG, "onActivityCreated")
}
///////////////////
class FragmentLeft : Fragment() {
val LOG_TAG = this::class.java.name
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(LOG_TAG, "onCreate")
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
Log.d(LOG_TAG, "onActivityCreated")
}
I think the issue comes from the fact that you defined your replaceTransaction method as generic, but you're not using T at all in that method, so type inference doesn't know what type to use in place of T.
To give you a simpler example, this will cause the same error:
fun <T> foo() {
println("Hello, world!")
}
fun main() {
foo()
}
That happens because T cannot be inferred, so you need to explicitly tell what type to use (even though it's not used at all in foo):
fun main() {
foo<Unit>() // I used Unit, but any other type would do
}
Given that, do you need T at all in your code? Both FragmentRight and FragmentLeft extend from Fragment, so unless you need to use specific functionalities from those classes, you can discard T and use the parent type Fragment (as you're already doing).
Instead of using t:Fragment, change the type of t to T, not Fragment
Try to write your extension function this way:
fun <T : Fragment> FragmentTransaction.replaceTransaction(layout: Int, t:
T): FragmentTransaction {
return this.replace(layout, t)
}
I am using libGDX inside android project as fragment all with kotlin and its working fine.
What i am trying to do is call a method of libgdx part of project from android part(MainActivity) of the project.
So for example if user presses on button which is made by android part,object in game will move.
First of all this is the project structure:
MainActivity:
package com.krytasoft.androidwithlibgdx
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
//import android.support.v4.app.Fragment throws unresolved error.without this compiles fine and works but shows type mismatch error.
import com.badlogic.gdx.backends.android.AndroidFragmentApplication
import com.krytasoft.gdxandroid.AndroidGameFragment
class MainActivity : AppCompatActivity(), AndroidFragmentApplication.Callbacks {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val libgdxGameFragment:AndroidGameFragment = AndroidGameFragment()
val button = findViewById<Button>(R.id.openFlexBoxTestButton)
val moveRightButton = findViewById<Button>(R.id.moveRightButton)
//never mind if this supportFragmentManager... shows type mismatch error.Its working. this line puts libgdx into fragment.fragment is similar to component in react.
supportFragmentManager.beginTransaction().replace(R.id.fragment_container, libgdxGameFragment, AndroidGameFragment::class.java.simpleName).commit()
button.setOnClickListener{
val intent = Intent(this, FlexBoxTestActivity::class.java)
startActivity(intent)
}
moveRightButton.setOnClickListener {
libgdxGameFragment.moveRight()
}
}
override fun exit() {
}
}
Here in MainActivity, notice moveRightButton.Its calling moveRight() function from fragment.
AndroidFragment class:
package com.krytasoft.gdxandroid
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration
import com.badlogic.gdx.backends.android.AndroidFragmentApplication
import com.krytasoft.mygdxgame.core.MyGdxGame
class AndroidGameFragment : AndroidFragmentApplication() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
val config = AndroidApplicationConfiguration()
return initializeForView(MyGdxGame(), config)
}
override fun startActivity(intent: Intent?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
fun moveRight(){
MyGdxGame().moveRight()
}
}
MyGDX Game:
package com.krytasoft.mygdxgame.core
import com.badlogic.gdx.ApplicationAdapter
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.Sprite
import com.badlogic.gdx.graphics.g2d.SpriteBatch
class MyGdxGame : ApplicationAdapter() {
lateinit var batch: SpriteBatch
lateinit var img: Texture
lateinit var sprite:Sprite
override fun create() {
batch = SpriteBatch()
img = Texture("badlogic.jpg")
sprite = Sprite(img)
println("create done from libgdx")
}
override fun render() {
Gdx.gl.glClearColor(1f, 0f, 0f, 1f)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
batch.begin()
batch.draw(sprite, 50f, 50f)
batch.end()
}
override fun dispose() {
batch.dispose()
img.dispose()
}
fun moveRight(){
sprite.x +=50f; // throws lateinit var sprite is uninitialzied error.
}
}
So what i expect is after pressing move right button,eventually call fun moveRight in mylibgdxgame and change position of sprite.
kotlin.UninitializedPropertyAccessException: lateinit property sprite has not been initialized
eventhough its initialized.But for some reason its not seen.
I uploaded my project to github:
https://github.com/lastpeony/libgdx-in-android-kotlin
Call create() method before using MyGdxGame instance. Also use a single instance of MyGdxGame across fragment.
class AndroidGameFragment : AndroidFragmentApplication() {
val myGdxGame = MyGdxGame()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
val config = AndroidApplicationConfiguration()
myGdxGame.create()
return initializeForView(myGdxGame, config)
}
fun moveRight(){
myGdxGame .moveRight()
}
}