问题
I have a button, and when i click to it, i make textView.setText()
a very big text, 50000 symbols, and the interface stops for 3 seconds, how can i fix it?
- I tried to make it with Handle and thread, but it hasn`t helped.
I tried to make
textview.append()
, but it also hasn`t helped.MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { textText.append(rowItemHeader.getText().substring((endOfNews - 10000, endOfNews)); } });
Edit 1 no result
private class MyTask extends AsyncTask <Void, Void, String> {
String str;
TextView txt;
MyTask(String str, TextView txt){
this.str = str;
this.txt = txt;
}
public String doInBackground(Void... args) {
return str.substring(endOfNews - 10000, endOfNews);
}
public void onPostExecute(String myString) {
// do your update here or you will get that error (the original thread one)
txt.append(myString);
}
}
回答1:
How did you declare the thread ? Yu've to use something like that :
this.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Log.e("TAG synchronize", "synchronize");
}
});
回答2:
Use AsyncTask, they are meant for exactly what you want. They are a secondary thread that is easy to setup and executes from your main thread.
Use a loop inside the thread that appends
portions of the generated text to the TextView
using runOnUiThread(new Runnable(...)...)
and call Thread.sleep(50)
which forces the Thread to sleep for that much milliseconds to prevent the lag.
回答3:
Use an AyncTask with something like:
private class MyTask extends AsyncTask<Void, Void, String> {
private Context context;
public MyTask(Context context) {
this.context = context;
}
public String doInBackground(Void... args) {
// do your job here
return myString;
}
public void onPostExecute(String myString) {
// do your update here or you will get that error (the original thread one)
((TextView)context.findViewById(R.id.textview)).setText(myString);
}
}
and then in your activity
new MyTask(MyActivity.this).execute();
回答4:
First, remove the view, then add the text on background thread, then add the view back. Tell me if you need some sample code.
来源:https://stackoverflow.com/questions/17277887/a-long-text-in-the-textview