首页 > 系统 > Android > 正文

Android自定义控件热身之scrollTo和scrollBy

2019-11-09 13:43:47
字体:
来源:转载
供稿:网友

View通过ScrollTo和ScrollBy 方法可以实现滑动。那么两者有什么区别呢?我们先来看一下源码

ScrollTo源码:

public void scrollTo(int x, int y) {      if (mScrollX != x || mScrollY != y) {          int oldX = mScrollX;          int oldY = mScrollY;          mScrollX = x;          mScrollY = y;          invalidateParentCaches();          onScrollChanged(mScrollX, mScrollY, oldX, oldY);          if (!awakenScrollBars()) {              invalidate(true);          }      }  }  ScrollBy 源码

public void scrollBy(int x, int y) {    scrollTo(mScrollX + x, mScrollY + y);}在代码中ScrollBy调用了ScrollTo

View.scrollTo(int x, int y):是View移动到坐标点(-x,-y)处。

View.scrollBy(int x, int y):是View相对当前位置滑动了(-x,-y)。(注:x为正值时向左滑动,y为正值时向上滑动)

scrollTo和scrollBy有两点需要注意:

①scrollTo(int x, int y)和scrollBy(int x, int y)在移动的时候它的坐标点与View的坐标系是"相反的",即当x为正数时View的横坐标为负值或向左移动,当y为正数时View的纵坐标为负值或向上移动。

②View.scrollTo(int x, int y)和View.scrollBy(int x, int y)移动的是View里面的内容并不是View本身,而且移动的是View里面内容的真实位置。下面我们通过一个Demo来验证一下

activity_main.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="com.havorld.scrolldemo.MainActivity" >    <Button        android:id="@+id/bt"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1"        android:gravity="left|top"        android:text="按钮一" />    <LinearLayout        android:id="@+id/ll"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1"        android:background="@android:color/holo_green_light" >        <Button            android:id="@+id/btn"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="按钮二" />    </LinearLayout></LinearLayout>

MainActivity.java
public class MainActivity extends Activity implements OnClickListener {	PRivate Button bt, btn;	private LinearLayout ll;	@Override	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		setContentView(R.layout.activity_main);		bt = (Button) findViewById(R.id.bt);		ll = (LinearLayout) findViewById(R.id.ll);		btn = (Button) findViewById(R.id.btn);		bt.setOnClickListener(this);		ll.setOnClickListener(this);		btn.setOnClickListener(this);	}	@Override	public void onClick(View v) {		switch (v.getId()) {		case R.id.bt:			bt.scrollTo(-100, -100);			break;		case R.id.ll:			ll.scrollBy(-10, -10);			break;		case R.id.btn:			Toast.makeText(this, "点击了按钮二", Toast.LENGTH_SHORT).show();			break;		default:			break;		}	}}当我们直接点击Button按钮时移动的是按钮里面的文字内容,当点击线性布局时移动的是布局里面的内容按钮,由此可以看出View.scrollTo(int x, int y)和View.scrollBy(int x, int y)移动的是所点击View里面的内容,而且移动后点击效果依然有效说明移动的是View内容的真实位置。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表