I'm trying to use Scroller to move a custom view, but the view doesn't move. Can anyone help me find what's wrong with my code?
public class CustomView extends View {
private Scroller mScroller;
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
mScroller = new Scroller(context);
}
public void smoothScrollTo(int destX, int destY) {
int scrollX = getScrollX();
int deltaX = destX - scrollX;
int scrollY = getScrollY();
int deltaY = destY - scrollY;
mScroller.startScroll(scrollX, scrollY, deltaX, deltaY, 1000);
invalidate();
}
@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
int currX = mScroller.getCurrX();
int currY = mScroller.getCurrY();
Log.d("SCROLL", "currX = " + currX + ", currY = " + currY);
scrollTo(currX, currY);
postInvalidate();
}
}
public class MainActivity extends AppCompatActivity {
private CustomView mCustomView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCustomView = (CustomView)findViewById(R.id.custom_view);
}
public void onStart(View view) {
mCustomView.smoothScrollTo(410, 200);
}
}
layout XML file:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.qihoo.scrollerdemo.MainActivity">
<com.sample.scrollerdemo.CustomView
android:id="@+id/custom_view"
android:background="#ff0"
android:layout_width="50dp"
android:layout_height="50dp" />
<Button
android:onClick="onStart"
android:text="start"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>