Scroller 界面滑动
Scroller 滑动之后滑动器子标签里面的控件,其自身是不动的.这里点在下面的进阶会体现出来.
1. 继承LinearLayout, 相对布局也可以.
public class MyLinearLayout extends LinearLayout {
private Scroller scroller;
public MyLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
scroller = new Scroller(context);
}
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
if (!scroller.isFinished()) scroller.abortAnimation();
scroller.startScroll(startX, startY, dx, dy, duration);
invalidate();
}
@Override
public void computeScroll() {
Log.d("cece", this.toString() + " computeScroll-----------");
if (scroller.computeScrollOffset()) {
scrollTo(scroller.getCurrX(), scroller.getCurrY());
postInvalidate();
}
}
}
2. 主界面
public class MyActivity extends Activity implements View.OnClickListener {
private static final String TAG = "MyActivity";
private Button button;
private MyLinearLayout linearLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
button = (Button) findViewById(R.id.button);
// imageView = (ImageView) findViewById(R.id.iv);
linearLayout = (MyLinearLayout) findViewById(R.id.rl);
button.setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
}
/**
* Called when a view has been clicked.
*
* @param v The view that was clicked.
*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
int x = linearLayout.getScrollX();
int y = linearLayout.getScrollY();
linearLayout.startScroll(x, y, 0, 100, 1000);
break;
case R.id.button2:
x = linearLayout.getScrollX();
y = linearLayout.getScrollY();
Log.d(TAG, "x:"+x+" y:"+y);
linearLayout.startScroll(x, y, 0, -100, 1000);
break;
}
}
}
3. 资源文件
<com.bytereal.luv.myapplication.MyLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_launcher" />
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button1" />
<!-- android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"-->
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button2" />
<!-- android:layout_alignTop="@+id/button"
android:layout_toStartOf="@+id/button"-->
</com.bytereal.luv.myapplication.MyLinearLayout>