/**
HorizontalScrollView -- 水平SCrollView
scrollbars -- 滚动条
*/
<ScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none"
>
<TextView
android:id="@+id/scroll_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</ScrollView>
public class ScrollActivity extends Activity implements View.OnClickListener{
private TextView tv;
private ScrollView scrollView;
private Button upbtn;
private Button downbtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scroll);
upbtn = (Button)findViewById(R.id.upbtn);
downbtn = (Button)findViewById(R.id.downbtn);
upbtn.setOnClickListener(this);
downbtn.setOnClickListener(this);
tv = (TextView)findViewById(R.id.scroll_text);
//或者value资源
tv.setText(getResources().getString(R.string.scroll_text));
scrollView = (ScrollView)findViewById(R.id.scrollView);
//代码禁止显示滚动条
scrollView.setHorizontalScrollBarEnabled(false);
scrollView.setVerticalScrollBarEnabled(false);
//滚动监听
scrollView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_UP:{//手指向上
break;
}
case MotionEvent.ACTION_DOWN:{//手指向下
break;
}
case MotionEvent.ACTION_MOVE:{//手指滑动
/**
* getScrollY() -- 滚到条滚动的距离
* getMeasuredHeight -- contentOffset
* getHeight() -- scroll的高度
* */
String str = "";
if (scrollView.getScrollY() <= 0){
str = "滑动到顶部";
}
//contentOffset <= scroll高度+滚动条距离
if (scrollView.getChildAt(0).getMeasuredHeight()<= scrollView.getHeight()+scrollView.getScrollY()){
str = "滑动到底部";
}
Toast.makeText(ScrollActivity.this,str,Toast.LENGTH_SHORT).show();
//textview添加内容
tv.append(getResources().getString(R.string.scroll_text));
break;
}
}
return false;
}
});
}
@Override
public void onClick(View v) {
//scrollTo:一直以滚动条的初始位置为初始位置,一旦设置就是跳到滚动位置
//scrollBy:以上一次的位置为初始位置
switch (v.getId()){
case R.id.upbtn:
{
scrollView.scrollTo(0,-30);
break;
}
case R.id.downbtn:
{
scrollView.scrollBy(0,30);
break;
}
}
}
}