简体   繁体   English

UIThread上的setText不起作用

[英]setText on UIThread not working

in my AsyncTask in the 在我的AsyncTask中

@Override
protected void onProgressUpdate(Void... values)

method, which runs on the UI-Thread i try to set Text of my MainLayout to "": 方法,该方法在UI线程上运行,我尝试将MainLayout的Text设置为“”:

LayoutInflater temporaryInflater = (LayoutInflater) myActivityContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View temporaryRootView = temporaryInflater.inflate(R.layout.myLayout, (ViewGroup) gv.getParent(), false);
        EditText temporaryEditText = (EditText) temporaryRootView.findViewById(R.id.myEdtiText);
        temporaryEditText.setText("");

This should work fine, i try to Change a view on the UIThread i provide a correct RootView with a rootViewGroup parent to provide LayoutParams but nothing happens. 这应该可以正常工作,我尝试更改UIThread上的视图,我提供了一个带有rootViewGroup父级的正确RootView以提供LayoutParams,但是什么也没有发生。 EditText stays with the old Text. EditText与旧的Text保持在一起。

Any suggestions? 有什么建议么? Would appreciate that. 将不胜感激。

Update regarding Rohan550's comments/hint : 关于Rohan550的评论/提示的更新

I will try your solution but isn't that the same(just for understanding): 我将尝试您的解决方案,但并非完全相同(仅用于理解):

public void resetEditText() {
    EditText temporaryEditText = (EditText) MyActivity.this.findViewById(R.id.myEditText);
    temporaryEditText.setText("");
}

which is in the Activity and in the AsyncTask on the UIThread in onProgressUpdate i call: 我在onProgressUpdate中的Activity和UIThread的AsyncTask中调用:

MyActivity wusch = new MyActivity();
wusch.resetEditText();

But it throws a NPE at findViewById in the resetEditText method.. 但是它将在resetEditText方法中的findViewById处引发NPE。

Why? 为什么?

Try to change: temporarySearchbar.setText(""); 尝试更改:temporalSearchbar.setText(“”); to temporaryEditText .setText(""); 临时文件.setText(“”);

AsyncTask can be broken if you add some library. 如果添加一些库,则AsyncTask可能会损坏。 for instance, admob or flurry. 例如admob或flurry。 dont assume onProgressUpdate will be in uithread even its feature is that. 不要假设onProgressUpdate将在uithread中,即使它的功能是那样。 so, try to use Handler. 因此,请尝试使用Handler。 create a handler in onCreate, then use it in onProgressUpdate this. 在onCreate中创建一个处理程序,然后在onProgressUpdate使用它。

Handler h = new Handler(); // in activity on create

then 然后

@Override
protected void onProgressUpdate(Void... values){
h.post(new Runnable() {
            @Override
            public void run() {
                // do ui operations
            }
        });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM