Reputation: 15
I'm trying to work on this example from a book. I keep receiving an "Unresolved reference: activity_main
" error. I am fairly new to Kotlin and Android Studio
. The code is show below.
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
activity_main.setOnTouchListener {_, m: MotionEvent ->
handleTouch(m)
true
}
}
Could you help me as to why Android Studio is throwing this error? Am I missing an import?
Upvotes: 0
Views: 1229
Reputation: 11
handleTouch is a function that you havent declared yet.
private fun handleTouch(m: MotionEvent)
{
val pointerCount = m.pointerCount
for (i in 0 until pointerCount)
{
val x = m.getX(i)
val y = m.getY(i)
val id = m.getPointerId(i)
val action = m.actionMasked
val actionIndex = m.actionIndex
var actionString: String
when (action)
{
MotionEvent.ACTION_DOWN -> actionString = "DOWN"
MotionEvent.ACTION_UP -> actionString = "UP"
MotionEvent.ACTION_POINTER_DOWN -> actionString = "PNTR DOWN"
MotionEvent.ACTION_POINTER_UP -> actionString = "PNTR UP"
MotionEvent.ACTION_MOVE -> actionString = "MOVE"
else -> actionString = ""
}
val touchStatus =
"Action: $actionString Index: $actionIndex ID: $id X: $x Y: $y"
if (id == 0)
binding.textView1.text = touchStatus
else
binding.textView2.text = touchStatus
}
}
Upvotes: 0
Reputation: 564
Yeah, activity_main
is your layout file and you can find it in res/layout
folder inside of your project.
activity_main.setOnTouchListener {_, m: MotionEvent ->
handleTouch(m)
true
}
this line makes no sense if inside of your activity_main
file you dont have view with id activity_main
. So, if you want to add touch listener to your root view inside of layout, just open activity_main
file and add android:id="@+id/root"
to your top view definition. Also, change activity_main.setOnTouchListener
to root.setOnTouchListener
. Android Studio will help you with imports of synthetic field
Upvotes: 2