查看高效,流畅的文本自动滚动

时间:2015-05-05 00:31:38

标签: android performance callback textview autoscroll

我想制作一个慢慢向下滚动的文本视图。

我能想到的一个明显的解决方案是使用TextView或其他东西,然后做一个反复向下滚动一小部分的回调,并在另外的1/24秒内自我注册。比如说。

这种方法效率很低吗?是否有更多电池友好的方式来实现相同的目标?

1 个答案:

答案 0 :(得分:0)

推荐的方法是使用postDelay方法,并在视图不可见后停止滚动。以下代码段是实现自动滚动的示例。希望它会有所帮助。

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);
}
}

布局中的TextView

<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" />