1、簡介
ScrollView是一個FrameLayout的容器,不過在他的基礎上添加了滾動,允許顯示的比實際多的內容!另外,只能夠往里面放置一個子元素,可以是單一的組件,又或者一個布局包裹着的復雜的層次結構!或者我們應該叫它豎直滾動條,對應的另外一個水平方向上的滾動條:HorizontalScrollView。
android:scrollbarThumbVertical //設置豎直滑塊 android:scrollbarThumbHorizontal //設置水平滑塊 android:scrollbars //設置滑塊顯示樣式(水平、豎直、不顯示) @Override //重寫滑動速度 public void fling(int velocityY) { super.fling(velocityY / 2); //速度變為原來的一半 } scrollView.fullScroll(ScrollView.FOCUS_DOWN); //滾動到底部 scrollView.fullScroll(ScrollView.FOCUS_UP); //滾動到頂部
2、簡單使用
布局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:gravity="center" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".LoginActivity"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/btn11" android:text="最底部"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/btn22" android:text="最頂部"/> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/scrollview" android:scrollbarThumbVertical="@drawable/rating_on" android:scrollbars="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textview"/> </ScrollView> </LinearLayout>
Java文件:
public class LoginActivity extends AppCompatActivity implements View.OnClickListener { private ScrollView scrollView; private TextView textView; private Button btn_up; private Button btn_down; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // Set up the login form. scrollView = (ScrollView)findViewById(R.id.scrollview); textView = (TextView)findViewById(R.id.textview); btn_down = (Button)findViewById(R.id.btn11); btn_up = (Button)findViewById(R.id.btn22); btn_up.setOnClickListener(this); btn_down.setOnClickListener(this); StringBuilder stringBuilder = new StringBuilder(); for (int i=0;i<100;i++){ stringBuilder.append("這是scrollview"+i+"\n"); } textView.setText(stringBuilder.toString()); } public void onClick(View v){ switch (v.getId()){ case R.id.btn11: scrollView.fullScroll(ScrollView.FOCUS_DOWN); break; case R.id.btn22: scrollView.fullScroll(ScrollView.FOCUS_UP); break; } } }