[英]Android ImageButton OnTouchListener not working
好吧,我发生了一件奇怪的事情。 我从其他布局导入了一个名为tab_btn的ImageButton,并导入了它并设置了onTouchListener可以正常工作。
包com.xx
导入kotlinx.android.synthetic.main.tab_btn_layout。*
导入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
}
})
}
}
在下面,我还有另一个来自btnNext布局的ImageButton。 我在上面设置了相同的OnTouchListener。 但这给了我错误。
而btnNext给我错误:
尝试在空对象引用上调用虚拟方法'void android.widget.ImageButton.setOnTouchListener(android.view.View $ OnTouchListener)'
注意:我已经导入了图像按钮的两种布局。 tab_btn工作正常,但btnNext不工作。
好吧,我解决了自己的问题。
真正的怀疑是我的btnNext在fragment(viewpager)中,我必须先在oncreateview方法中将rootview膨胀。
注意:如果不膨胀片段,就无法访问该片段的元素。
这是ma代码:
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
}
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.