[英]Locate fragment view elements and update them after asynctask is done
我有一個活動可以容納多個片段。 每個片段都實現我的UpdateRequest接口,其中每個片段都執行一些asynctask並從Web服務下載數據。 我的問題是我不太了解如何更新現有片段。 我讀了這個
但是我仍然不知道如何找到每個片段的視圖然后更新它們。 我舉一個例子:
有一個UserFragment,它應該代表用戶個人資料:
public class UserFragment extends SherlockFragment implements
UpdateRequest {
View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_user_info,
container, false);
return rootView;
}
...
public void update(final OnFragmentUpdatedListener context) {
...
asyntask
...
}
}
而fragment_user_info看起來像這樣:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/fragment_user_picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/image_of_user" />
<TextView
android:id="@+id/fragment_user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/user_info" />
</RelativeLayout>
我想要的是找到UserFragment的實例,然后在其AsyncTask.onPostExecute()方法中將fragment_user_name textView中的文本更改為asynctask返回的內容。
最簡單的方法是在片段中創建最終變量,以保存對TextView的引用。 然后,作為片段的匿名內部類的AsyncTask將可以直接訪問它。 因此,如下所示:
公共類UserFragment擴展SherlockFragment實現UpdateRequest {
private View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_user_info, container, false);
return rootView;
}
...
public void update(final OnFragmentUpdatedListener context) {
final TextView userNameView = (TextView) rootView.findViewById(R.id.fragment_user_name);
...
asyntask
...
onPostExecute() {
userNameView.setText(....);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.