我正在尝试使用Scroller移动自定义视图,但视图不会移动。任何人都可以帮我找到我的代码有什么问题吗?
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);
}
}
布局XML文件:
<?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>