带有TextWatcher的Android多线程 [英] Android MultiThreading with TextWatcher

查看:92
本文介绍了带有TextWatcher的Android多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Android开发还很陌生,目前正在开发一个应用程序,该应用程序使人们可以在框中输入文本,并将文本显示在屏幕上的位图上.

I'm fairly new to Android development and am currently working on an app that allows people to type text into a box and the text is displayed on a Bitmap on screen.

我在活动中有一个文本框,用于监听更改.每次键入文本时,它都会调用函数来找出如何最佳设置图像上文本的格式,然后使用新文本更新图像.它仅适用于少量文本,但工作量很大时,计算速度变慢,设备开始冻结,几乎无法输入.

I have a text box in the activity that listens for changes. Each time you type text it calls functions to figure out how to best format the text on the image, then updates the image with the new text. It works fine for just a little bit of text, but when there's a lot, the calculations become slower and the device begins to freeze up, making typing nearly impossible.

有没有一种方法可以在后台运行计算,以便在框内键入内容不受图像更新的影响?我认为使用多个线程会很有用,但对线程的了解不足以使其正常工作.

Is there a way I can run the calculations in the background so that typing in the box is unaffected by the image updating? I'm thinking that using multiple threads would be useful, but don't know enough about threading to get it functioning.

这是我的代码:

public class PicTextWatcher implements TextWatcher {
    ...
    public void afterTextChanged(Editable editable) {
        pic.setText(editable.toString());         //This function is relatively slow
        pic.writeText();                          //This function is very slow
        imageView.setImageBitmap(pic.getImage()); //This doesn't need to happen every keystroke, only when the other functions have completely finished
    }
}

预先感谢, 格林斯特先生

Thanks in advance, MrGrinst

推荐答案

您可以使用AsyncTask在后台执行操作

You can use AsyncTask to do things in the background

public void afterTextChanged(final Editable editable) {
    new AsyncTask<Void, Void, Void>() {
        protected Void doInBackground(Void... params) {
            pic.setText(editable.toString());
            pic.writeText();
            return null;
        }
        protected void onPostExecute(Void result) {
            imageView.setImageBitmap(pic.getImage());
        }            
    }.execute();
}

您必须记住,如果用户键入速度快而writetext速度慢,则现在可能会同时多次调用pic.setText(editable.toString());pic.writeText();.

You have to remember that now pic.setText(editable.toString());pic.writeText(); may be called simultaneously multiple times if the user typing fast and writetext is slow.

这篇关于带有TextWatcher的Android多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆