【问题标题】:How to force a view to redraw immediately before saving it as an image如何强制视图在将其保存为图像之前立即重绘
【发布时间】:2014-08-23 08:53:48
【问题描述】:

我有一个自定义的TextView,我将其视为EditText 视图。用户按下共享按钮,包含TextView 的布局将保存为 PNG 图像并共享到社交网络。

我的问题是TextView 中有一个光标字符。在创建图像之前,我想删除光标字符。但是,如果我以创建和共享图像的相同方法删除角色,应用程序会崩溃,因为它没有机会先重绘视图。

我的问题和How to force a view to redraw immediately before the next line of code is executed基本一样,但是和这个问题不同的是我不需要改变后台资源。

我尝试调用invalidate(),但这并不能解决问题,因为在我需要视图之前,UI 从来没有机会重绘。

我该怎么办?

这是我的代码:

public void shareToOtherApps(View v) {

    RelativeLayout messageOutline = (RelativeLayout) findViewById(R.id.rlMessageOutline);

    // Remove cursor from display (inputWindow is a TextView)
    inputWindow.setText(converter
            .unicodeToFontReadable(unicodeText.toString()));
    inputWindow.invalidate(); // This line makes no difference

    // Code to save image
    messageOutline.setDrawingCacheEnabled(true);
    Bitmap bitmap = messageOutline.getDrawingCache(true);
    ...

    // Code to share image
    ...

    // Add cursor back to display
    updateDisplay();
}

【问题讨论】:

    标签: android view redraw


    【解决方案1】:

    我解决了这个问题,但是将代码保存/共享图像放在runnable 中,并在删除光标字符后运行它。这会将runnable 代码放在消息堆栈的末尾,并允许 UI 在尝试保存视图图像之前更新其视图。

    这里是代码摘要:

    public void shareToOtherApps(View v) {
    
        // Remove cursor from display (inputWindow is a TextView)
        inputWindow.setText(converter.unicodeToFontReadable(unicodeText.toString()));
    
        // Put this in a runnable to allow UI to update itself first
        inputWindow.post(new Runnable() {
            @Override
            public void run() {
    
                // Code to save image
                RelativeLayout messageOutline = (RelativeLayout) findViewById(R.id.rlMessageOutline);
                messageOutline.setDrawingCacheEnabled(true);
                Bitmap bitmap = messageOutline.getDrawingCache(true);
    
                // Code to share image
                ...
    
                // Add cursor back to display
                updateDisplay();
            }
        });
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-05
      • 1970-01-01
      • 2015-06-21
      • 2023-03-23
      • 1970-01-01
      • 2012-06-22
      相关资源
      最近更新 更多