Search code examples
androiddialogimageviewinvalidationui-thread

Invalidating and ImageView outside of the MainActivity thread


My MainActivity's contentView/View can be refresh by simply using invalidate() anywhere after calling:

setContentView(R.layout.activity_main);

But if I were to call a Dialog in my item select:

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch(item.getItemId()){
    case R.id.menu_tools:
        showDialog();
        return true;
            ...

Doing this does not refresh the ImageView inside the Dialog:

public class ToolSettingsDialog extends Dialog {
                ...
private void updatePreview() {
    ImageView image = (ImageView)findViewById(R.id.widthImageView);

    Bitmap bitmap = Bitmap.createBitmap(400, 400, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    bitmap.eraseColor(Color.WHITE);

    Drawing d = null;
    d = box.getDrawing();
    s.draw(paint, canvas);
    image.setImageBitmap(bitmap);
    image.invalidate();     
}

I've been looking all around and I can't seem to understand how to invalidate in different thread than the UI one.


Solution

  • Dialogs are drawn on the UI thread, similarly to all other UI operations on Android. So that probably isn't your problem.

    Also, you cannot do UI operations off the UI thread. You would have to perform the invalidate() on the UI thread, using something like View.postInvalidate() or Activity.runOnUIThread().