java从AsyncTask(片段内)访问TextView
首先,我对安卓编程还不熟悉,所以如果这个问题看起来很愚蠢,我很抱歉,我仍在努力解决这个问题! 我试图从onPostExecute()异步任务中更新片段中的文本视图。 但我正在努力从布局中获取文本视图并进行更新。 我似乎能够动态创建TextView并对其进行更新,但我想创建一个在xml布局中创建的TextView。我在这里看到了大量类似的问题,但没有一个使用片段(这是我试图学习的片段)
你可以从下面的代码中看到,我最初尝试在代码中创建文本视图(tv)(注释掉),效果很好。然后我尝试从布局((TextView)rootView)中获取TextView。findviewbyd(R.id.tv2)),但由于无法将其声明为公共字符串,因此我现在无法在onPostExecute()中访问它
我是不是在做傻事
public static class PlaceholderFragment extends Fragment {
String str;
//public TextView tv;
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tug_boat_main,
container, false);
tv = (TextView)rootView.findViewById(R.id.tv2);
//tv = new TextView(container.getContext());
tv.setText("hi there");
ReadExtPortfolio rext = new ReadExtPortfolio();
rext.execute();
return tv;
//return rootView;
}
class ReadExtPortfolio extends AsyncTask<Void, Void, Void>
{
@Override
protected void onPreExecute() {
tv.setText("Fetching data, please wait: ");
}
@Override
protected Void doInBackground(Void... arg0) {
try {
URL url = new URL("http://mywebsite.com/andy.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
str = in.readLine();
in.close();
} catch (IOException e) {
str = "error";
}
return null;
}
// Executed on the UI thread after the
// time taking process is completed
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
tv.setText("Completed the task, and the result is : " + str);
}
}
}
XML文件(fragment_tug_boat_main)包含
<TextView
安卓:id="@+id/tv2"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:text="@string/hello_world2" />
而且,我已经使用stackoverflow多年了,这些年来,回答问题的人为我节省了数小时的工作时间。因此,感谢阅读本文,感谢所有回答的人
编辑: 对不起,我应该说的。如果我取消注释“公共文本视图电视”然后我得到一个运行时错误:指定的子级已经有了父级。必须首先对孩子的父对象调用removeView()。我不认为调用removeView()听起来正确,因为我的TextView上不存在removeView
# 1 楼答案
你所要做的就是取消注释//公共文本查看电视;然后你就可以在onPostExecute方法中使用它了