背景
在很多情况下我们可能见过像类似显示歌词页面,出来一句歌词就自动将页面向上滚动并且定位到最底部,简单回忆并实现xml中创建和动态创建两种情况。
- 第一种是在xml中创建布局
- 第二种是动态生成的布局
分析
当然textview想要实现垂直滚动,我们可以将其外层嵌套一个ScrollView,设置好两个属性 android:fadeScrollbars=”false”和android:scrollbars=”vertical”,这是什么意思呢:fadeScrollbars就是是否显示滑动按钮,当然scrollbars是滑动的方向。
实例
一如既往,以实际演示为主更容易学会使用
- xml创建布局
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="@color/colorAccent"
android:fadeScrollbars="false"
android:scrollbars="vertical">
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fadeScrollbars="false"
android:scrollbars="vertical"
android:textSize="25sp"/>
</ScrollView>
<Button
android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/scrollView"
android:text="增加"
android:textSize="25sp"/>
</RelativeLayout>
- MainActivity代码
public class MainActivity extends AppCompatActivity {
TextView mTextView;
ScrollView mScrollView;
Button mButton;
int count;
Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.textview);
mScrollView = (ScrollView) findViewById(R.id.scrollView);
mButton = (Button) findViewById(R.id.btn_add);
mTextView.setMovementMethod(ScrollingMovementMethod.getInstance());
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
count++;
mTextView.append("\r\n");
mTextView.append(count + "");
scrollToBottom(mScrollView, mTextView);
}
});
}
/**
* 根据scrolview 和子view去测量滑动的位置
*
* @param scrollView
* @param view
*/
private void scrollToBottom(final ScrollView scrollView, final View view) {
handler.post(new Runnable() {
@Override
public void run() {
if (scrollView == null || view == null) {
return;
}
// offset偏移量。是指当textview中内容超出 scrollview的高度,那么超出部分就是偏移量
int offset = view.getMeasuredHeight()
- scrollView.getMeasuredHeight();
if (offset < 0) {
offset = 0;
}
//scrollview开始滚动
scrollView.scrollTo(0, offset);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (handler != null) {
handler = null;
}
}
}
- 效果展示
动态生成的可自行练习,思路是用悬浮窗实现。