ScrollView(滚动条)-UI组件-Android
是一个容器,继承FrameLayout
fullScroll()
滚动方法:
- 滚动到底部
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
- 滚动到顶部
scrollView.fullScroll(ScrollView.FOCUS_UP);
隐藏滑块:android:scrollbars="none"
设置滚动速度
继承ScrollView,然后重写一个 public void fling (int velocityY)的方法:
@Override
public void fling(int velocityY) {
super.fling(velocityY / 2); //速度变为原来的一半
}
注意:ScrollView控件中只能包含一个View或一个ViewGroup
案例
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn_down"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="滚动到底部" />
<Button
android:id="@+id/btn_up"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="滚动到顶部" />
<ScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none"
android:layout_weight="1">
<TextView
android:id="@+id/txt_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<!--: ScrollView控件中只能包含一个View或一个ViewGroup,放多了会崩溃-->
<!-- <TextView-->
<!-- android:layout_width="wrap_content"-->
<!-- android:layout_height="wrap_content"/>-->
</ScrollView>
</LinearLayout>
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class ScrollViewActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_down;
private Button btn_up;
private ScrollView scrollView;
private TextView txt_show;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scrollview_layout);
bindViews();
}
private void bindViews() {
btn_down = (Button) findViewById(R.id.btn_down);
btn_up = (Button) findViewById(R.id.btn_up);
scrollView = (ScrollView) findViewById(R.id.scrollView);
txt_show = (TextView) findViewById(R.id.txt_show);
btn_down.setOnClickListener(this);
btn_up.setOnClickListener(this);
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 100; i++) {
sb.append("我是一条文本内容 * " + i + "
");
}
txt_show.setText(sb.toString());
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_down:
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
break;
case R.id.btn_up:
scrollView.fullScroll(ScrollView.FOCUS_UP);
break;
}
}
}