2013-03-27 50 views
5

我在水平滾動視圖中添加了線性佈局,並在佈局中添加了一些文本視圖。是否有可能在此佈局中顯示可見的孩子。Horizo​​ntalScrollView得到可見的孩子

這個代碼讓所有的孩子,但我想只得到可見(當前顯示的)孩子:

final HorizontalScrollView scroll = (HorizontalScrollView)findViewById(R.id.horizontalScrollView1); 
    LinearLayout linearLayout = ((LinearLayout)scroll.findViewById(R.id.linearLayout1)); 
    int chilrenNum = linearLayout.getChildCount(); 
+0

你的意思是'可見的孩子是setVisibilty(View.VISIBLE)'嗎?或者你的意思是「看得見」? – 2013-03-27 09:22:19

+0

我的意思是看得見。 – user2106897 2013-03-27 09:47:58

回答

3

好了,經過一個有點搜索上,所以我發現這個答案聽滾動事件。 Implement Scroll Event Listener in Android。 這個想法是在你的ScrollView中覆蓋onScrollChanged,並跟蹤你的活動中可視部分的滾動視圖。

這樣做,你可以很容易地通過類似如下的代碼獲得可見的觀點:

int currentPosition = lastXPosition; // lastXPosition gets updated from scroll event 
int layoutWidth = linearLayout.getWidth(); 
Display display = getWindowManager().getDefaultDisplay(); 
Point size = new Point(); 
display.getSize(size); 
int width = size.x; 
int childWidth = layoutWidth/linearLayout.getChildCount(); 
int firstVisibleXPos = currentPosition - width/2; // currentPosition will be in the middle of the screen 
int lastVisibleXPos = currentPosition + width/2; 

int indexOfFirstVisible = firstVisibleXPos/childWidth; 
int indexOfLastVisible = lastVisibleXPos/ childWidth; 

所有上面的代碼假定固定子視圖大小。如果您使用的是可變子尺寸,則需要首先獲取它們的寬度並跟蹤它,然後根據父視圖中的索引和位置計算可見性。

+0

在這一行中得到錯誤:display.getSize(size); – user2106897 2013-03-27 10:06:06

+0

我用導入android.view.Display; – user2106897 2013-03-27 10:06:31

+0

try int width = display.getWidth();反而看起來你正在對抗2.x級別 – 2013-03-27 10:08:57