一、ScrollView介紹
滾動視圖是指當擁有很多內容,屏幕顯示不完時,需要通過滾動來顯示完整的視圖
二、ScrollView的種類
HorizontalScrollView:水平滾動視圖
ScrollView:垂直滾動視圖
<HorizontalScrollView
android:id="@+id/scroll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none">
<TextView
android:id="@+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</HorizontalScrollView>
三、隱藏ScrollView
(1)標籤屬性:android:scrollbars=”none”
(2)代碼設置:
setHorizontalScrollBarEnabled(false);隱藏橫向ScrollView
setVerticalScrollBarEnabled(false);隱藏縱向ScrollView
四、setOnTouchListener的使用
應用案例:判斷ScrollView何時滑動到底部
public class MainActivity extends AppCompatActivity {
private TextView tv;
private ScrollView scroll;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv= (TextView) findViewById(R.id.content);
tv.setText(getResources().getString(R.string.content));
scroll = (ScrollView) findViewById(R.id.scroll);
scroll.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()){
case MotionEvent.ACTION_MOVE:
{
/**
* (1)getScrollY()---滾動條滑動的距離
* (2)getMeasuredHeight()獲取的整個高度
* (3)getHeight()
*/
//頂部狀態
if(scroll.getScrollY()<=0)
{
Log.i("Main", "頂部");
}
//底部狀態
//TextView的總高度<=一屏幕的高度+滾動條的滾動距離
if(scroll.getChildAt(0).getMeasuredHeight()<=scroll.getHeight()+scroll.getScrollY()){
Log.i("Main","底部");
Log.i("Main","scroll.getChildAt(0).getMeasuredHeight()<=scroll.getHeight()="+scroll.getChildAt(0).getMeasuredHeight()+"scrol,getHeight()="+scroll.getHeight()+"scroll.getScrollY()="+scroll.getScaleY());
tv.append(getResources().getString(R.string.content));//滑動到底部追加新的文字
}
break;
}
}
return false;
}
});
}
五、控制ScrollView視圖位置
1、scrollTo和ScrollBy區別
應用案例:控制ScrollView視圖位置
@Override
public void onClick(View view) {
switch (view.getId()){
//scrollTo:以滾動視圖其實位置開始計算
//scrollBy:相對前一次位置,去滾動對應的距離
case R.id.up:
{
scroll.scrollTo(0,-30);
break;
}
case R.id.down:
{
scroll.scrollTo(0,30);
break;
}
}
}