Skip to content

Instantly share code, notes, and snippets.

@Mirochiu
Last active May 25, 2020 06:19
Show Gist options
  • Save Mirochiu/1c3f5012781338bcd156787b1ec63e1d to your computer and use it in GitHub Desktop.
Save Mirochiu/1c3f5012781338bcd156787b1ec63e1d to your computer and use it in GitHub Desktop.
Auto scrolling TextView in constraint layout
// in your onCreate of MainActivity.java
final TextView txtMsgView = findViewById(R.id.textView);
txtMsgView.setMovementMethod(new ScrollingMovementMethod()); // Let users use the mouse or touchpad to move the scroll
txtMsgView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
txtMsgView.post(new Runnable() {
@Override
public void run() {
if (txtMsgView.getLineHeight() * txtMsgView.getLineCount() >= txtMsgView.getHeight()) {
txtMsgView.setGravity(Gravity.BOTTOM | Gravity.LEFT);
} else {
txtMsgView.setGravity(Gravity.TOP | Gravity.LEFT);
}
}
});
}
});
// a buttton for testing auto scrolling
Button btn = findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener(){
int _counter = 0;
@Override
public void onClick(View view) {
runOnUiThread(new Runnable() {
@Override
public void run() {
txtMsgView.append("this is test " + _counter + "\n");
Log.d("TEST","text" + _counter);
_counter++;
}
});
}
});
/*
in your activity_main.xml
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toTopOf="@id/nav_view"
android:background="@color/colorAccent"
android:focusable="false"
android:scrollbars="vertical"
android:gravity="top|left"
android:text="msg\n" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent" />
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment