UI线程上的setText不起作用

时间:2014-11-29 11:40:44

标签: android android-edittext

中的AsyncTask中

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

方法,在UI-Thread上运行我尝试将我的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("");

这应该工作正常,我尝试更改UIThread上的视图我提供一个正确的RootView与rootViewGroup父提供LayoutParams但没有任何反应。 EditText保留旧文本。

有什么建议吗?很感激。

关于Rohan550的评论/提示更新

我会尝试你的解决方案但不一样(只是为了理解):

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

在Activity中和onProgressUpdate中的UIThread上的AsyncTask中调用:

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

但它会在findViewById方法{...}}处抛出一个NPE。

为什么呢?

2 个答案:

答案 0 :(得分:0)

尝试更改:temporarySearchbar.setText("");到temporaryEditText .setText("");

答案 1 :(得分:0)

如果添加一些库,

AsyncTask可能会被破坏。例如,admob或flurry。不要假设onProgressUpdate即使其功能也是如此。所以,尝试使用Handler。在onCreate中创建一个处理程序,然后在onProgressUpdate中使用它。

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

然后

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