如何让click事件传递给android中的容器?

前端之家收集整理的这篇文章主要介绍了如何让click事件传递给android中的容器?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个FrameLayout表,其中每个帧包含 ImageView或TextView.无论帧中的内容如何,​​我都希望通过帧上的OnClickListener检测onClick事件.

我怎样才能做到这一点?

这是我的一些布局,我总共有5行(这里只显示1行).
如上所述,每行有5个FrameLayouts,每个包含一个TextView.我无法将OnClickListener放在TextView上,因为这可能会在运行时更改为ImageView.因此我想在FrameLayout上使用OnClickListener.

似乎FrameLayout的内容阻止它检测到click事件.

  1. <TableLayout
  2. android:layout_width="fill_parent"
  3. android:layout_height="fill_parent"
  4. android:id="@+id/gateContainer"
  5. android:stretchColumns="*">
  6.  
  7. <TableRow
  8. android:layout_width="fill_parent"
  9. android:layout_height="fill_parent"
  10. android:layout_gravity="center">
  11.  
  12. <FrameLayout
  13. android:layout_width="fill_parent"
  14. android:layout_height="fill_parent"
  15. android:id="@+id/door1"
  16. android:clickable="true">
  17.  
  18. <TextView
  19. android:layout_width="fill_parent"
  20. android:layout_height="fill_parent"
  21. android:text="New Text"
  22. android:id="@+id/textView"
  23. android:layout_gravity="center" />
  24.  
  25. </FrameLayout>
  26.  
  27. <FrameLayout
  28. android:layout_width="fill_parent"
  29. android:layout_height="fill_parent"
  30. android:id="@+id/door2" >
  31.  
  32. <TextView
  33. android:layout_width="fill_parent"
  34. android:layout_height="fill_parent"
  35. android:text="New Text"
  36. android:id="@+id/textView5"
  37. android:layout_gravity="center" />
  38. </FrameLayout>
  39.  
  40. <FrameLayout
  41. android:layout_width="fill_parent"
  42. android:layout_height="fill_parent"
  43. android:id="@+id/door3" >
  44.  
  45. <TextView
  46. android:layout_width="fill_parent"
  47. android:layout_height="fill_parent"
  48. android:text="New Text"
  49. android:id="@+id/textView4"
  50. android:layout_gravity="center"/>
  51. </FrameLayout>
  52. </TableLayout>

这是我如何设置OnClickListeners的示例:

  1. View.OnClickListener clickListener = new View.OnClickListener() {
  2. @Override
  3. public void onClick(View v){
  4. // do something
  5. }
  6. };
  7.  
  8. TableLayout tableLayout = (TableLayout) findViewById(R.id.gateContainer);
  9. // Go through all TableRows
  10. for (int i = 0; i < tableLayout.getChildCount(); i++){
  11. TableRow tableRow = (TableRow) tableLayout.getChildAt(i);
  12. // Set listener for each FrameView
  13. for (int j = 0; j < tableRow.getChildCount(); j++){
  14. FrameLayout frame = (FrameLayout) tableRow.getChildAt(j);
  15.  
  16. frame.setOnClickListener(clickListener);
  17. }
  18. }

解决方法

只需在ImageView和TextView组件上实现OnTouchListener并将它们放在一边即可传递它们.
  1. <your_view>.setOnTouchListener(new OnTouchListener(){
  2.  
  3. @Override
  4. public boolean onTouch(View v,MotionEvent event) {
  5. // TODO Auto-generated method stub
  6. return true;
  7. }
  8.  
  9. });

这将确保您的容器处理.

猜你在找的Android相关文章