[英]Android Fragment Update TextView From AsyncTask onPostExecute
I have an AsyncTask that uses HttpGet to fetch content from a remote server. 我有一个使用HttpGet从远程服务器获取内容的AsyncTask。 I have tested and this is working fine, now I want to update a TextView with the result of this AsyncTask.
我已经测试过,并且工作正常,现在我想使用此AsyncTask的结果更新TextView。 Here is what I have done.
这是我所做的。
From the OnCreateView of the Fragment, I get reference to a Button and a TextView, I initially hide the TextView and then in the OnClickListener for the button I want to unhide the textview and update that textview with the result of my AsyncTask 从片段的OnCreateView中,获得对Button和TextView的引用,首先隐藏TextView,然后在OnClickListener中找到要取消隐藏文本视图并使用AsyncTask结果更新该文本视图的按钮
View rootView = inflater.inflate(R.layout.fragment_programs_list, container, false);
Button btnLoadPrograms = (Button) rootView.findViewById(R.id.btnLoadPrograms);
TextView tvShowPrograms = (TextView) rootView.findViewById(R.id.tvRestCall);
tvShowPrograms.setVisibility(View.GONE);
btnLoadPrograms.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startNewAsyncTask();
}
});
return rootView;
Now in the onPostExecute of the AsyncTask, I want to update the Textview 现在,在AsyncTask的onPostExecute中,我想更新Textview
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
getView().findViewById(R.id.tvRestCall).setVisibility(View.SHOW); //Does not exit
}
How do I get a reference to the TextView from within the AsyncTask in a Fragment and then update that TextView with the result of the doinbackground. 如何从Fragment中的AsyncTask中获取对TextView的引用,然后使用doinbackground的结果更新该TextView。
尝试使用getView().findViewById(R.id.tvRestCall).setVisibility(View.VISIBLE);
Try this way, 试试这个
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvShowPrograms.setVisibility(View.VISIBLE);
}
我同意https://stackoverflow.com/users/1113949/ksarmalkar-您可以发送对AsyncTask的引用,然后使用该引用通过mYourView.setVisibility(View.VISIBLE);
设置可见性mYourView.setVisibility(View.VISIBLE);
I ended up solving the issue as follows Set a public property for the textView 我最终解决了以下问题,为textView设置了一个公共属性
public TextView tvShowPrograms;
Then in OnCreateView I initialize the TextView and set the text to null 然后在OnCreateView中,我初始化TextView并将文本设置为null
tvShowPrograms = (TextView) rootView.findViewById(R.id.tvRestCall);
tvShowPrograms.setText("");
And then the onPostExecute, I simply set the textView to the result. 然后在onPostExecute上,我只是将textView设置为结果。
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvShowPrograms.setText(result);
}
Thanks for the answers, I am glad it is working 感谢您的回答,我很高兴它正在工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.