OK. What I\'m trying to achieve is a layout that does the same effect as frozen panes in Excel. That is I want a header row that scrolls horizontally with the main ListView
Try Below solution it works in my case
leftlist.setOnScrollListener(new SyncedScrollListener(rightlist));
rightlist.setOnScrollListener(new SyncedScrollListener(leftlist));
SyncedScrollListener.java
package com.xorbix.util;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
public class SyncedScrollListener implements OnScrollListener{
int offset;
int oldVisibleItem = -1;
int currentHeight;
int prevHeight;
private View mSyncedView;
public SyncedScrollListener(View syncedView){
if(syncedView == null){
throw new IllegalArgumentException("syncedView is null");
}
mSyncedView = syncedView;
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int[] location = new int[2];
if(visibleItemCount == 0){
return;
}
if(oldVisibleItem != firstVisibleItem){
if(oldVisibleItem < firstVisibleItem){
prevHeight = currentHeight;
currentHeight = view.getChildAt(0).getHeight();
offset += prevHeight;
}else{
currentHeight = view.getChildAt(0).getHeight();
View prevView;
if((prevView = view.getChildAt(firstVisibleItem - 1)) != null){
prevHeight = prevView.getHeight();
}else{
prevHeight = 0;
}
offset -= currentHeight;
}
oldVisibleItem = firstVisibleItem;
}
view.getLocationOnScreen(location);
int listContainerPosition = location[1];
view.getChildAt(0).getLocationOnScreen(location);
int currentLocation = location[1];
int blah = listContainerPosition - currentLocation + offset;
mSyncedView.scrollTo(0, blah);
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
}
This thread has helped me find a solution for a similar problem I've been struggling with for a while. It is also based on intercepting touch events. In this case the syncing works for multiple listviews and is entirely symmetric.
The major challenge was to prevent list item clicks to propagate to the other listviews. I need clicks and long clicks dispatched only by the listview that initially received the touch event, including in particular the highlight feedback when you just touch down on an item (intercepting onClick event is no use since it's too late in the calling hierarchy).
The key to this is intercepting the touch event twice. First, the initial touch event is relayed to the other listviews. The same onTouch handler function catches these and feeds them to a GestureDetector. In the GestureDetector
callbacks the static touch events (onDown
etc.) are consumed (return true
) whereas the motion gestures aren't (return false
) such that they can be further dispatched by the view itself and trigger the scrolling.
Using setPositionFromTop
inside onScroll
didn't work for me because it makes the scrolling behavior extremely sluggish. OnScroll is used instead to align initial scroll positions as new ListViews are added to the Syncer.
The only problem that persists so far is the one brought up by s1ni5t3r above. If you double-fling the listView then they still become disconnected.
public class ListScrollSyncer
implements AbsListView.OnScrollListener, OnTouchListener, OnGestureListener
{
private GestureDetector gestureDetector;
private Set<ListView> listSet = new HashSet<ListView>();
private ListView currentTouchSource;
private int currentOffset = 0;
private int currentPosition = 0;
public void addList(ListView list)
{
listSet.add(list);
list.setOnTouchListener(this);
list.setSelectionFromTop(currentPosition, currentOffset);
if (gestureDetector == null)
gestureDetector = new GestureDetector(list.getContext(), this);
}
public void removeList(ListView list)
{
listSet.remove(list);
}
public boolean onTouch(View view, MotionEvent event)
{
ListView list = (ListView) view;
if (currentTouchSource != null)
{
list.setOnScrollListener(null);
return gestureDetector.onTouchEvent(event);
}
else
{
list.setOnScrollListener(this);
currentTouchSource = list;
for (ListView list : listSet)
if (list != currentTouchSource)
list.dispatchTouchEvent(event);
currentTouchSource = null;
return false;
}
}
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
if (view.getChildCount() > 0)
{
currentPosition = view.getFirstVisiblePosition();
currentOffset = view.getChildAt(0).getTop();
}
}
public void onScrollStateChanged(AbsListView view, int scrollState) { }
// GestureDetector callbacks
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; }
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; }
public boolean onSingleTapUp(MotionEvent e) { return true; }
public boolean onDown(MotionEvent e) { return true; }
public void onLongPress(MotionEvent e) { }
public void onShowPress(MotionEvent e) { }
}
edit: the double-fling issue can be resolved by using a state variable.
private boolean scrolling;
public boolean onDown(MotionEvent e) { return !scrolling; }
public void onScrollStateChanged(AbsListView view, int scrollState)
{
scrolling = scrollState != SCROLL_STATE_IDLE;
}
According to Sam instructions I developed a simple app showing scrolling two listviews together. Actually my main purpose is to create a horizontally scrolling expandable listview with fixed/frozen columns and working on it when finished, will share it soon https://github.com/huseyinDaVinci/Android/tree/master/FrozenListViews
Rewrite
I didn't have much luck with passing the scrolling actions in one ListView to another. So I chose a different method: passing the MotionEvent
. This lets each ListView
calculate their own smooth scroll, fast scroll, or anything else.
First, we'll need some class variables:
ListView listView;
ListView listView2;
View clickSource;
View touchSource;
int offset = 0;
Every method that I add to listView
will be almost identical for listView2
, the only difference is that listView2
will reference listView
(not itself). I didn't include the repetitive listView2
code.
Second, let's start with the OnTouchListener:
listView = (ListView) findViewById(R.id.engNameList);
listView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(touchSource == null)
touchSource = v;
if(v == touchSource) {
listView2.dispatchTouchEvent(event);
if(event.getAction() == MotionEvent.ACTION_UP) {
clickSource = v;
touchSource = null;
}
}
return false;
}
});
To prevent circular logic: listView
calls listView2
calls listView
calls... I used a class variable touchSource
to determine when a MotionEvent
should be passed. I assumed that you don't want a row click in listView
to also click in listView2
, so I used another class variable clickSource
to prevent this.
Third, the OnItemClickListener:
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(parent == clickSource) {
// Do something with the ListView was clicked
}
}
});
Fourth, passing every touch event isn't perfect because occasional discrepancies appear. The OnScrollListener is perfect for eliminating these:
listView.setOnScrollListener(new OnScrollListener() {
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(view == clickSource)
listView2.setSelectionFromTop(firstVisibleItem, view.getChildAt(0).getTop() + offset);
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
});
(Optional) Lastly, you mentioned that you have trouble since listView
and listView2
begin at different heights in your layout... I highly recommend modifying your layout to balance the ListViews, but I found a way to address this. However it is a little tricky.
You cannot calculate the difference in height between the two layouts until after the entire layout have been rendered, but there is no callback for this moment... so I use a simple handler:
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// Set listView's x, y coordinates in loc[0], loc[1]
int[] loc = new int[2];
listView.getLocationInWindow(loc);
// Save listView's y and get listView2's coordinates
int firstY = loc[1];
listView2.getLocationInWindow(loc);
offset = firstY - loc[1];
//Log.v("Example", "offset: " + offset + " = " + firstY + " + " + loc[1]);
}
};
I assume that a half second delay is long enough to render the layout and start the timer in onResume()
:
handler.sendEmptyMessageDelayed(0, 500);
If you do use an offset I want to be clear that listView2
's OnScroll method subtracts the offset rather than adds it:
listView2.setSelectionFromTop(firstVisibleItem, view.getChildAt(0).getTop() - offset);
Hope that helps!
OK. I have an answer now. The problem being that .setSelectionFromTop() would only work if the listview was in the top layout (ie. not nested). Afters some head scratching I realised that I could make my layout a RelativeLayout and get the same look but without having to nest layouts for the checkbox and listview. This is the new layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/recordViewLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<CheckBox android:id="@+id/checkBoxTop"
android:text="Check All"
android:layout_width="160dp"
android:layout_height="wrap_content"/>
<ListView android:id="@+id/engNameList"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:layout_below="@+id/checkBoxTop"/>
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/checkBoxTop">
<LinearLayout android:id="@+id/scroll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<include layout="@layout/record_view_line" android:id="@+id/titleLine" />
<ListView
android:id="@android:id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent"/>
</LinearLayout>
</HorizontalScrollView>
</RelativeLayout>
This basically is the code that goes with the layout.
In onCreate()
engListView=getListView();
engListView.setOnTouchListener(this);
recordListView=(ListView)findViewById(R.id.recordList);
recordListView.setOnScrollListener(this);
and the listener methods:
public boolean onTouch(View arg0, MotionEvent event) {
recordListView.dispatchTouchEvent(event);
return false;
}
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
View v=view.getChildAt(0);
if(v != null)
engListView.setSelectionFromTop(firstVisibleItem, v.getTop());
}
I resolve it by changing ListView to RecyclerView , use RecyclerView .addOnScrollListener for synchronizing the scroll event. And there is not discrepancies,it's perfect!
private void syncScrollEvent(RecyclerView leftList, RecyclerView rightList) {
leftList.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return rightList.getScrollState() != RecyclerView.SCROLL_STATE_IDLE;
}
});
rightList.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return leftList.getScrollState() != RecyclerView.SCROLL_STATE_IDLE;
}
});
leftList.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (recyclerView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE) {
rightList.scrollBy(dx, dy);
}
}
});
rightList.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (recyclerView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE) {
leftList.scrollBy(dx, dy);
}
}
});
}