Last active
December 2, 2020 10:54
-
-
Save cachapa/d350079977b4f85fc338 to your computer and use it in GitHub Desktop.
An Android view for showing logs in realtime - useful for debugging
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.annotation.TargetApi; | |
import android.content.Context; | |
import android.os.Build; | |
import android.util.AttributeSet; | |
import android.widget.ScrollView; | |
import android.widget.TextView; | |
import java.util.Locale; | |
public class LogView extends ScrollView { | |
private long mCreationTime = System.currentTimeMillis(); | |
private TextView mTextView; | |
public LogView(Context context) { | |
super(context); | |
init(); | |
} | |
public LogView(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
init(); | |
} | |
public LogView(Context context, AttributeSet attrs, int defStyleAttr) { | |
super(context, attrs, defStyleAttr); | |
init(); | |
} | |
@TargetApi(Build.VERSION_CODES.LOLLIPOP) | |
public LogView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { | |
super(context, attrs, defStyleAttr, defStyleRes); | |
init(); | |
} | |
private void init() { | |
mTextView = new TextView(getContext()); | |
addView(mTextView); | |
} | |
public void log(String message) { | |
long elapsedTime = System.currentTimeMillis() - mCreationTime; | |
long seconds = elapsedTime / 1000; | |
long milliseconds = elapsedTime % 1000; | |
if (mTextView.getText().length() > 0) { | |
mTextView.append("\n"); | |
} | |
String formattedLog = String.format(Locale.getDefault(), "T+%d.%03d: %s", seconds, milliseconds, message); | |
mTextView.append(formattedLog); | |
} | |
@Override | |
protected void onLayout(boolean changed, int l, int t, int r, int b) { | |
super.onLayout(changed, l, t, r, b); | |
smoothScrollTo(0, mTextView.getHeight()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment