[英]Accessing a TextView from AsyncTask (within a fragment)
首先,我是android編程的新手,所以很抱歉,如果這看起來像是一個愚蠢的問題,我仍在努力使自己全神貫注! 我正在嘗試從onPostExecute()AsyncTask內部的片段中更新TextView。 但是我正在努力如何從布局中獲取一個TextView並更新它。 我似乎能夠即時創建TextView並對其進行更新,但是我想使用在xml布局中創建的Textview。 我在這里看到了很多類似的問題,但是沒有一個人使用片段(我嘗試學習的片段片段)。
您可以從下面的代碼中看到,我首先嘗試在代碼中創建TextView(tv)(注釋掉),並且效果很好。 然后我嘗試從布局((TextView)rootView.findViewById(R.id.tv2))中獲取TextView,但是由於無法將其聲明為公共字符串,因此現在無法在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
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world2" />
另外,我已經使用stackoverflow多年了,那些年來回答問題的人為我節省了很多時間。 因此,感謝您閱讀本文並感謝所有回答。
編輯:對不起,我應該說。 如果我取消注釋“ public TextView tv”; 然后我得到一個運行時錯誤:指定的子代已經有一個父代。 您必須先在子級父級上調用removeView()。 我不認為調用removeView()聽起來很正確,因為TextView不存在removeView
您要做的就是取消注釋// public TextView tv; 然后您將可以在onPostExecute方法中使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.