標籤:
ScrollView 的使用相對來講比較簡單,通過包含更多的布局檔案,使得上下滑動可以瀏覽到更多內容。
關於ScrollView有幾個點需要注意的地方
1,ScrollView的滾動方式
ScrollView有兩種滾動方式,橫向的和縱向的,一般橫向的用的比較少。ScrollView控制項預設就是縱向滾動的,如果需要橫向滾動只需要更改標籤
HorizontalScrollView,即可滿足要求
2,ScrollView預設是在滾動的過程中顯示捲軸的,所以如果想隱藏捲軸有兩種方式:
1,通過標籤設定:android:scrollbars=“none”
2, 通過代碼設定:setHorizontalScrollBarEenable(false);setVertivalScrollBarEnable(false);
3,ScrollView的常用方法:
1,getScrollY()-----返回的是捲軸滑動的距離
2,getMeasureHeight()------返回的是scrollView的總高度,也就是 滾動的距離+螢幕的寬度
3,getHeight()-------返回的是顯示出來的scroll的高度
4,ScrollTo 和ScrollBy的區別
1,ScrollTo :從scroll的開始位置作為參考,進行滾動的距離
2,ScrollBy:從scroll的當前位置作為參考,進行滾動的距離
public class MainActivity extends Activity implements View.OnClickListener{ private TextView textView; private ScrollView scrollView; private Button up; private Button down; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView)findViewById(R.id.textView); scrollView = (ScrollView)findViewById(R.id.scroll); textView.setText(R.string.text); up = (Button)findViewById(R.id.button); down = (Button)findViewById(R.id.button2); scrollView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()){ case MotionEvent.ACTION_MOVE:{ if(scrollView.getScaleY()<=0){ android.util.Log.i("main","top"); } if(scrollView.getMeasuredHeight() == scrollView.getHeight()+scrollView.getScaleY()){ android.util.Log.i("main","bottom"); } break; } } return false; } }); } @Override public void onClick(View v) { switch(v.getId()){ case R.id.button:{ scrollView.scrollBy(0, -30); break; } case R.id.button2:{ scrollView.scrollBy(0,30); break; } } }}
ScrollView布局檔案如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="top" android:id="@+id/button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="down" android:id="@+id/button2" /> </LinearLayout> <ScrollView android:id="@+id/scroll" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollbars="none"> <TextView android:id="@+id/textView" android:text="@string/hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </ScrollView></LinearLayout>
android學習ScrollView的使用