Okay, there's a weird thing happening in me. I have an ImageButton named tab_btn from other layout which I imported and set onTouchListener which is working.
package com.xx
import kotlinx.android.synthetic.main.tab_btn_layout.*
import kotlinx.android.synthetic.main.btnNext_layout.*
class EventDetails : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_event_details)
tab_btn.setOnTouchListener(object : View.OnTouchListener {
override fun onTouch(view: View?, event: MotionEvent?): Boolean {
if (event!!.action == MotionEvent.ACTION_DOWN) {
val icon: Drawable = ContextCompat.getDrawable(applicationContext, R.drawable.talk_bt_tab)
icon.setColorFilter(Color.GRAY,PorterDuff.Mode.MULTIPLY)
tab_btn.setImageDrawable(icon)
}else if (event!!.action == MotionEvent.ACTION_UP) {
tab_btn.clearColorFilter()
}
return true
}
})
btnNext.setOnTouchListener(object : View.OnTouchListener {
override fun onTouch(p0: View?, ev: MotionEvent?): Boolean {
if (ev!!.action == MotionEvent.ACTION_DOWN){
val icon: Drawable = ContextCompat.getDrawable(applicationContext, R.drawable.layer_bt_next)
icon.setColorFilter(Color.GRAY,PorterDuff.Mode.MULTIPLY)
btnNext.setImageDrawable(icon)
}else if(ev!!.action == MotionEvent.ACTION_UP){
btnNext.clearColorFilter()
}
return true
}
})
}
}
and below that I have another ImageButton from other layout named btnNext. I set the same OnTouchListener on it. But it gives me error .
And btnNext gives me error:
Attempt to invoke virtual method 'void android.widget.ImageButton.setOnTouchListener(android.view.View$OnTouchListener)' on a null object reference
note: I have imported both layout of the Image button. tab_btn is working but btnNext is not working.
Okay, I solved my own problem.
The real suspect is that my btnNext is in the fragment(viewpager) which I have to inflate first the rootview in oncreateview method.
note: you cannot access the element of the fragment without inflating it.
here's ma code:
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
val rootView = inflater!!.inflate(R.layout.btnNext_layout, container, false)
var next : ImageButton = rootView.findViewById(R.id.btnNext)
next.setOnTouchListener(object : View.OnTouchListener {
override fun onTouch(p0: View?, ev: MotionEvent?): Boolean {
if (ev!!.action == MotionEvent.ACTION_DOWN){
val icon: Drawable = ContextCompat.getDrawable(activity.applicationContext, R.drawable.layer_bt_next)
icon.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY)
btn_next.setImageDrawable(icon)
}else if (ev!!.action == MotionEvent.ACTION_UP){
val icon: Drawable = ContextCompat.getDrawable(activity.applicationContext, R.drawable.layer_bt_next)
icon.setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY)
btn_next.setImageDrawable(icon)
}
return true
}
})
}