ScrollView 种类:
1.HorizontalScrollView:水平滚动视图
2.ScrollView:垂直滚动视图(常用类)
public class MainActivity extends AppCompatActivity { private TextView text; private ScrollView scrollView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //注册控件 text = (TextView) findViewById(R.id.txt); scrollView = (ScrollView) findViewById(R.id.scrollview); //设置text文本内容 text.setText(getResources().getString(R.string.context)); //设置ScrollView滚动条不可见 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:{ //顶部状态 if(scrollView.getScrollY() <= 0){ Log.i( "main", "到达顶部"); } //底部状态 //TextView的总高度 <= 一屏幕的高度 + 滚动条的滚动距离 if(scrollView.getChildAt(0).getMeasuredHeight() <= scrollView.getHeight() + scrollView.getScrollY()){ Log.i("main","到达底部" + "总高度" + scrollView.getChildAt(0).getMeasuredHeight() + "一屏幕高度" + scrollView.getHeight() + "滚动条滚动距离" + scrollView.getScrollY()); //添加内容 text.append(getResources().getString(R.string.context)); } break; } } return false; } }); }
按钮滚动
scrollTO(x,y) 跳转到固定坐标
scrollBy(x,y)相对当前位置移动x,y
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //注册控件 text = (TextView) findViewById(R.id.txt); scrollView = (ScrollView) findViewById(R.id.scrollview); up_btn = (Button) findViewById(R.id.up); down_btn = (Button)findViewById(R.id.down); //按钮点击监控事件 up_btn.setOnClickListener(this); down_btn.setOnClickListener(this); //设置text文本内容 text.setText(getResources().getString(R.string.context)); //设置ScrollView滚动条不可见 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:{ //顶部状态 if(scrollView.getScrollY() <= 0){ Log.i( "main", "到达顶部"); } //底部状态 //TextView的总高度 <= 一屏幕的高度 + 滚动条的滚动距离 if(scrollView.getChildAt(0).getMeasuredHeight() <= scrollView.getHeight() + scrollView.getScrollY()){ Log.i("main","到达底部" + "总高度" + scrollView.getChildAt(0).getMeasuredHeight() + "一屏幕高度" + scrollView.getHeight() + "滚动条滚动距离" + scrollView.getScrollY()); //添加内容 text.append(getResources().getString(R.string.context)); } break; } } return false; } }); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.up:{ scrollView.scrollBy(0,-30); break; } case R.id.down:{ scrollView.scrollBy(0,+30); break; } } }