我正在尝试启动一个线程在while循环内执行一段代码。问题是UI挂起,并且进度对话框在显示后立即停止。删除处理程序对象时,它运行良好,但是UI不会发生任何变化。有什么问题吗?
MainActivity类
app_name = 'cart'
urlpatterns = [
path('add_books/', views.add_books, name='add_to_cart')
]
StringUtils类
public class MainActivity extends AppCompatActivity {
...
Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
mProgressDialog.dismiss();
mTextOutput.setText(mRepeatedText);
}
};
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("Text Repeater");
mProgressDialog.setMessage("We're generating your text...");
mProgressDialog.show();
Runnable mRunnable = new Runnable() {
@Override
public void run() {
mRepeatedText = StringUtils.repeat(mText, mNumberOfIterations);
mHandler.sendEmptyMessage(0);
}
};
mThread = new Thread(mRunnable);
mThread.start();
答案 0 :(得分:0)
在StringUtils类中重复的方法中的return语句似乎不在正确的位置。这可能是您要寻找的:
public class StringUtils {
public static String repeat(String text, int numberOfIterations) {
StringBuilder buffer = new StringBuilder(text.length()*numberOfIterations);
while(numberOfIterations-- > 0){
buffer.append(text);
}
return buffer.toString();
}
}
答案 1 :(得分:0)
问题出在这行代码中:
mTextOutput.setText(mRepeatedText);
当使用大量迭代时,例如100,000次。这将使我输入的单词,句子或其他内容得到100,000份。并且将所有这些加载到textview中需要花费时间。