Skip to content

Instantly share code, notes, and snippets.

@arnaudbos
Created August 1, 2011 23:24
Show Gist options
  • Save arnaudbos/1119232 to your computer and use it in GitHub Desktop.
Save arnaudbos/1119232 to your computer and use it in GitHub Desktop.
(Android)Create a ScrollView synchronizer
<!-- Use this in place of the classic ScrollView you want to use -->
<path.to.package.SynchronizerScrollView
android:id="@+id/synchronizer_scrollview"
android:...
>
...
</path.to.package.SynchronizerScrollView>
public interface ScrollViewListener
{
void onScrollChanged(SynchronizerScrollView scrollView, int x, int y, int oldx, int oldy);
}
import android.app.Activity;
import android.os.Bundle;
public class SynchronizedScrollActivity extends Activity implements ScrollViewListener
{
private SynchronizerScrollView scrollView1 = null;
private ScrollView scrollView2 = null;
// or
// private SynchronizerScrollView scrollView2 = null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
scrollView1 = (SynchronizerScrollView) findViewById(R.id.scrollview1);
scrollView1.setScrollViewListener(this);
scrollView2 = (ScrollView) findViewById(R.id.scrollview2);
// or
// scrollView2 = (SynchronizerScrollView) findViewById(R.id.scrollview2);
// scrollView2.setScrollViewListener(this);
}
public void onScrollChanged(SynchronizerScrollView scrollView, int x, int y, int oldx, int oldy)
{
scrollView2.scrollTo(x, y);
// or
// if(scrollView == scrollView1)
// {
// scrollView2.scrollTo(x, y);
// }
// else if(scrollView == scrollView2)
// {
// scrollView1.scrollTo(x, y);
// }
}
}
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;
public class SynchronizerScrollView extends ScrollView
{
private ScrollViewListener scrollViewListener = null;
public SynchronizerScrollView(Context context)
{
super(context);
}
public SynchronizerScrollView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
public SynchronizerScrollView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public void setScrollViewListener(ScrollViewListener scrollViewListener) {
this.scrollViewListener = scrollViewListener;
}
@Override
protected void onScrollChanged(int x, int y, int oldx, int oldy) {
super.onScrollChanged(x, y, oldx, oldy);
if(scrollViewListener != null) {
scrollViewListener.onScrollChanged(this, x, y, oldx, oldy);
}
}
}
Thanks to @Andy on StackOverflow question: http://stackoverflow.com/questions/3948934/synchronise-scrollview-scroll-positions-android
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment