2013-05-27 25 views
12

我有一個滾動視圖與很多因素OnClickListener上滾動視圖

ScrollView scroller = (ScrollView)findViewById(R.id.scrollView); 

我需要一個onClickListener附加到滾動型的,所以我做

scroller.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       // This is all you need to do to 3D flip 
       AnimationFactory.flipTransition(viewAnimator, FlipDirection.LEFT_RIGHT); 
      } 

     }); 

但是,這是沒有得到觸發,當我碰。有任何想法嗎?

+0

你肯定是沒有得到觸發?嘗試記錄它或在onClick方法中顯示Toast並查看它是否工作。 – Ahmad

+0

是的,我試過。它沒有被觸發。那裏面有很多的子視圖,那是因爲那個嗎? –

回答

8

這是因爲ScrollView的孩子正在獲取用戶的觸摸事件而不是ScrollView。您必須爲ScrollView的每個孩子設置clickable = false屬性,使onClickListener能夠在ScrollView上工作。

否則,備用可以設置每個ScrollView的孩子的onClickListener並處理它。

5

最好的解決方案似乎把LinearLayout納入ScrollView並在其上設置setOnClickListener

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 

    <LinearLayout 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:id="@+id/myLayout" 
     android:clickable="true" 
     android:orientation="vertical"> 

     <!-- content here --> 
    </LinearLayout> 
</ScrollView> 

的活動:

LinearLayout lin = (LinearLayout) fragment.rootView.findViewById(R.id.myLayout); 

lin.setOnTouchListener(new setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      // Whatever 
     } 
}); 
4

您需要直接設置setOnClickListener上滾動型的孩子

由於ScrollView可以只有一個孩子,你可以簡單地使用這種方法:

ScrollView scrollView = //... 

View.OnClickListener mOnClickListener = new View.OnClickListener() { 
    @Override 
    public void onClick(View view) { 
     // ... 
} 

//Set the onClickListener directly on the ScrollView's child 
scrollView.getChildAt(0).setOnClickListener(mOnClickListener); 
+0

這是正確的答案。它的工作原理,並在這裏建議的替代方案...是不理想的。 – aaaidan

+0

這個解決方案唯一的問題是,你必須等到'ScrollView'的孩子被添加到樹中,然後才能設置偵聽器。這不是很好,但我只是用一個帖子等待這種情況發生之前,我運行'getChildAt(0)' – aaaidan