Domanda

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.

Here's my code:

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

È stato utile?

Soluzione

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

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top