Scrollview - TextView - 滚动的最佳技巧是什么

时间:2017-07-24 19:44:29

标签: android scroll textview scrollview

我的应用程序正在记录文本信息,我使用的技术基于嵌入ScrollView的TextView,其中包含完整的字符串。

这种方法的真正缺点是随着时间的推移,字符串变得非常大,如果不是崩溃,你可以体验到的最好的是性能下降,因为系统是outOfMemory。

我可以使用的其他技术是什么?

以下是我提出的代码:

public class MainActivity extends AppCompatActivity {
    boolean run = true;
    String str = "", t;
    int i = 0;
    TextView txt;
    ScrollView sv;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txt = (TextView) findViewById(R.id.txt);
        Button btn = (Button) findViewById(R.id.btn);
        sv = (ScrollView) findViewById(R.id.sv);

        t = "this is the log for monday the 24th of july 2017 - number ";


        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                start();
            }
        });

    }

    private void start(){
        new Timer().schedule(new TimerTask() {

            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    public void run() {
                        i++;
                        str = str + t + i + "\n";
                        txt.setText(str);
                        sv.fullScroll(ScrollView.FOCUS_DOWN);
                    }
                });
            }
        }, 0, 100);
    }
}

和布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.narb.log.MainActivity">

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="Start"
        />

    <ScrollView
        android:id="@+id/sv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:layout_below="@id/btn"
        >

        <TextView
            android:id="@+id/txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="This is the log number"
            android:layout_margin="15dp"
            />
    </ScrollView>
</RelativeLayout>

1 个答案:

答案 0 :(得分:1)

取代 str = str + t + i +“\ n”; txt.setText(str);
尝试使用 str = t + i +“\ n”; txt.setText(txt.getText()+ str);
或者你也可以简单地使用 txt.setText(txt.getText()+ t + i +“\ n”);

相关问题