A recommended way is using the postDelay
method, and stop the scrolling after the view invisible. The following code snippet is an example to implement the auto scrolling. Hope it would be helpful.
public class MainActivity extends ActionBarActivity implements Runnable {
private TextView textView;
private String[] lines = new String[] { "line 11111111111111111111111",
"line 22222222222222222222222", "line 33333333333333333333333",
"line 44444444444444444444444", "line 55555555555555555555555" };
private final int NUM_OF_LINES = lines.length;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textview);
}
/*
* (non-Javadoc)
*
* @see android.support.v4.app.FragmentActivity#onResume()
*/
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
textView.postDelayed(this, 1000);
}
/*
* (non-Javadoc)
*
* @see android.support.v4.app.FragmentActivity#onPause()
*/
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
textView.removeCallbacks(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void run() {
// TODO Auto-generated method stub
String[] dst = new String[NUM_OF_LINES];
System.arraycopy(lines, 1, dst, 0, NUM_OF_LINES - 1);
dst[NUM_OF_LINES - 1] = lines[0];
StringBuilder builder = new StringBuilder();
for (int i = 0; i < NUM_OF_LINES; i++) {
builder.append(dst[i]);
if (i != NUM_OF_LINES - 1) {
builder.append("\n");
}
}
textView.setText(builder.toString());
lines = dst;
textView.postDelayed(this, 1000);
}
}
And the TextView
in the layout.
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lines="5"
android:maxLines="5"
android:singleLine="false"
android:text="@string/hello_world" />