scroller组件位于android.widget包中,主要的功能是处理组件的平滑滑动,如果想立即产生移动的效果调用view的scrollTo()和scrollBy()方法就可以了。scroller组件可以作用于view组件或者是viewgroup组件,作用于view组件的时候是控制组件内部的移动,例如textView中的文字。作用于viewgroup的时候,控制内部组件的移动。一般都是作用于ViewGroup类型。
自定义的layout如下:
package com.app.main;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Scroller;
public class MyLayout extends ViewGroup {
Scroller scroller = null;
public MyLayout(Context context, AttributeSet attrs) {
super(context, attrs);
scroller=new Scroller(this.getContext());
}
public MyLayout(Context context) {
super(context);
}
public void setScroll(int deta)
{
scroller.startScroll(scroller.getCurrX(), scroller.getCurrY(), -deta, 0);
this.invalidate();
}
@Override
public void computeScroll() {
if(scroller.computeScrollOffset())
{
this.scrollTo(scroller.getCurrX(), scroller.getCurrY());
this.postInvalidate();
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
for(int i=0;i<this.getChildCount();i++)
{
View v=this.getChildAt(i);
v.layout(l, t, r, b);
}
}
}
layout.xml:
<LinearLayout 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"
android:orientation="vertical"
tools:context=".Main" >
<com.app.main.MyLayout
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="300sp"
android:background="#EEA9B8" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="aa" />
</com.app.main.MyLayout>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="slide" />
</LinearLayout>
main.java:
package com.app.main;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Main extends Activity {
MyLayout layout = null;
Button btn = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
layout = (MyLayout) this.findViewById(R.id.layout);
btn = (Button) this.findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
layout.setScroll(30);
}
});
}
}
实现的效果如下:
在使用过程中,最重要的方法就是startScroll()和computeScrollOffset()两个方法。startScroll()方法并不是开始产生动画效果,而是对一些值进行了赋值的操作,而在computScrollOffset中将移动的距离分成了一小段一小段的,然后调用scrollTo(),这样看起来就是动画的效果了。