Friday, June 29, 2018
TextView auto scroll down to display bottom of text
TextView auto scroll down to display bottom of text
This example show how to make a TextView auto scroll down to display bottom of text. In the demonstration, the upper TextView is normal, user cannot see the bottom of text if it is full. The lower one, the TextView will auto scroll down, such that user can see the new added text.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android_layout_width="match_parent"
android_layout_height="match_parent"
android_padding="16dp"
android_orientation="vertical"
tools_context="com.blogspot.android_er.androidautotextview.MainActivity">
<TextView
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_layout_margin="20dp"
android_layout_gravity="center_horizontal"
android_autoLink="web"
android_text="http://android-er.blogspot.com/"
android_textStyle="bold"/>
<EditText
android_id="@+id/textin"
android_layout_width="match_parent"
android_layout_height="wrap_content"
android_textSize="28dp"/>
<Button
android_id="@+id/btnappend"
android_layout_width="match_parent"
android_layout_height="wrap_content"
android_text="Append Text"/>
<LinearLayout
android_layout_width="match_parent"
android_layout_height="match_parent"
android_orientation="vertical">
<TextView
android_id="@+id/textout1"
android_layout_width="match_parent"
android_layout_height="0dp"
android_layout_weight="1"
android_textSize="20dp"
android_background="#D0D0D0"/>
<TextView
android_id="@+id/textout2"
android_layout_width="match_parent"
android_layout_height="0dp"
android_layout_weight="1"
android_textSize="20dp"
android:gravity="bottom"
android_background="#E0E0E0"/>
</LinearLayout>
</LinearLayout>
package com.blogspot.android_er.androidautotextview;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText editTextIn;
TextView textViewOut1, textViewOut2;
Button btnAppend;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextIn = (EditText)findViewById(R.id.textin);
btnAppend = (Button)findViewById(R.id.btnappend);
textViewOut1 = (TextView)findViewById(R.id.textout1);
textViewOut1.setText("Its normal TextView. ");
textViewOut2 = (TextView)findViewById(R.id.textout2);
textViewOut2.setMovementMethod(new ScrollingMovementMethod());
textViewOut2.setText("This TextView always auto scroll down to display bottom of text. ");
btnAppend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String textToAppend = editTextIn.getText().toString() + " ";
textViewOut1.append(textToAppend);
textViewOut2.append(textToAppend);
editTextIn.setText("");
}
});
}
}