package cc.ac; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.app.Activity; /** * Demo描述: * 对ViewGroup调用scrollTo()和scrollBy()方法. * * 验证理论: * 假如一个ViewGroup(比如此处的XXXLayout)调用了scrollTo(By)() * 它的Content(即它所有的子View)都会移动. * * 参考资料: * 1 http://blog.csdn.net/wangjinyu501/article/details/32339379 * 2 http://blog.csdn.net/qinjuning/article/details/7247126 * Thank you very much * * 备注说明: * 使用scrollTo(By)()方法移动过程较快而且比较生硬. * 为了优化scrollTo(By)()的滑动过程可采用Scroller类. * 该类源码第一句This class encapsulates scrolling. * 就指明了该类的目的:封装了滑动过程. * 在后面的示例中,将学习到Scroller的使用. */ public class MainActivity extends Activity { private LinearLayout mLinearLayout; private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init(){ mLinearLayout=(LinearLayout) findViewById(R.id.linearLayout); mButton=(Button) findViewById(R.id.button); mButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mLinearLayout.scrollBy(-50, 0); } }); } }
main.xml如下:
<RelativeLayout 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" > <LinearLayout android:id="@+id/linearLayout" android:layout_width="fill_parent" android:layout_height="300dip" android:background="@android:color/darker_gray" > <TextView android:layout_width="150dip" android:layout_height="50dip" android:background="@android:color/black" android:text="@string/hello_world" android:textColor="@android:color/white" /> </LinearLayout> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:text="BUTTON" /> </RelativeLayout>