【问题标题】:ViewFlipper's onTouch event is NOT fired while its child Button's onClick event isViewFlipper 的 onTouch 事件不会被触发,而其子 Button 的 onClick 事件是
【发布时间】:2012-04-19 14:58:59
【问题描述】:

我一直在努力在 StackOverflow 或其他地方寻找解决方案,但我找不到任何关于这个特定问题的直接帖子,也许除了我再也找不到的可能最接近的帖子。但是,如果这仅仅是因为我忽略了某些事情或者我只是一个大菜鸟,请提前道歉。

无论如何,我正在尝试将 OnTouchListener 设置为 ViewFlipper(父级)并将 setOnClickListener 设置为填充父级布局的按钮(子级)。我希望首先调用 ViewFlipper 的 onTouch() 事件。想如果 ViewFlipper 的 onTouch() 返回 false,Button 的 onClick() 会被触发。但是,只调用了 Button 的 onClick()。为什么?有没有明确的优先级?

或者,我可以为 Button 设置一个 onTouchListener,因为 Button 具有 'match_parent' 属性,所以触摸这个 viewflipper 与触摸这个按钮实际上是一样的,即使我这样做了,它只会使 Button 的 onClick()事件未触发......

以下是我的简化活动;

public class TestActivity extends Activity implements OnTouchListener, View.OnClickListener {
@Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ViewFlipper vf = (ViewFlipper) findViewById(R.id.viewFlipper1);
    Button btn = (Button) this.findViewById(R.id.btnTest1);
    vf.setOnTouchListener(this);
    btn.setOnClickListener(this);

}

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ViewFlipper
    android:id="@+id/viewFlipper1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <include
        android:id="@+id/button"
        layout="@layout/test" />
</ViewFlipper>
</LinearLayout>

test.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/testLinear"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:orientation="vertical" >
<Button
    android:id="@+id/btnTest1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Button" />
</LinearLayout>

【问题讨论】:

    标签: android onclick


    【解决方案1】:

    我仍然不明白为什么没有首先调用 ViewFlipper 的 onTouch 事件,但我找到了一种方法来逃避这个问题。我们可以将 onClickListener 和 onTouchListener 都设置为按钮。

    btn.setOnClickListener(this);
    btn.setOnTouchListener(this);
    

    正如在原帖中所说,它阻止了 onClick() 事件的发生,但无论如何?如果不是android系统调用的,那就手动调用吧。

    @Override public boolean onTouch (View v, MotionEvent event) {
    
    // walls of codes 
    
    this.onClick(v);
    

    我知道我需要一些调整。如果用户花费超过 0.5 秒的时间将手指从屏幕上移开,我不会将其称为“点击”。

    【讨论】:

      猜你喜欢
      • 2013-03-12
      • 2013-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-24
      • 2013-04-25
      • 2014-09-18
      • 1970-01-01
      相关资源
      最近更新 更多