簡體   English   中英

如何在Android中完成AsyncTask后更新片段?

[英]How to update a Fragment after an AsyncTask finishes in Android?

可能有一種非常簡單的方法,只需要一行或兩行代碼,但我不知道如何解決這個問題。

我希望最初在屏幕中央顯示加載gif的片段,然后它將啟動AsyncTask,從我的服務器下載信息。 AsyncTask完成后,我需要將Fragment的內容視圖設置為不同的xml文件,然后顯示我從服務器獲得的一些內容。

我認為應該有一些類型的功能,如Fragment.invalidate()Fragment.refresh() ,可以幫助更新片段,但我似乎無法找到任何這樣的功能。

另外,如果我在onCreateView函數之外的其他函數中更新Fragment,是否需要創建變量來保存最初傳遞給它的LayoutInflaterViewGroup對象,還是可以使用函數調用來訪問它們? 以下是我想做的事情......

public class HomeFragment extends Fragment
{
    public HomeFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.loading, container, false);

        (new GetDataTask()).execute(1);

        return view;
    }


    private class GetDataTask extends AsyncTask<Integer, Void, ServerResponse>
    {
        @Override
        protected void onPreExecute(){}

        @Override
        protected ServerResponse doInBackground(Integer... args)
        {
            int page_num = args[0];
            return Server.getPosts(page_num);
        }

        @Override
        protected void onPostExecute(ServerResponse result)
        {
            /*
                1. Update the content view to R.layout.multi_post_list
                2. Change specific text views and image views (I know how to do this part)
                3. Notify that changes have been made to the Fragment, so it needs redrawn
            */
        }
    }
}

注意: ServerResponse是我創建的類,Server.getPosts是一個返回ServerResponse的靜態函數。 我知道這些都適用於我的情況。 我需要幫助我的GetDataTask類的onPostExecute部分中的第1點和第3點。

謝謝!

您可以使用findFragmentByTag

DetailsFragment df = getFragmentManager().findFragmentByTag("details");
    if (df != null) {
        df.setShownIndex(getSelectedIndex());
    } else {
        df = DetailsFragment.newInstance(getSelectedIndex());
    }
    fragmentTransaction.replace(R.id.frame, df, "details").commit();

三件事:

  1. 使用AsyncTaskLoader而不是AsyncTask來防止在屏幕旋轉后重新加載數據。 或者在Fragment上調用setRetainInstance(true)以防止片段在旋轉時被破壞。 (只是要小心處理分離狀態)
  2. 您可以通過調用getActivity().findViewById(android.R.id.content)來獲取Activity的根視圖,並根據需要對其進行操作。 您還可以創建一個具有兩種狀態並顯示/隱藏部分狀態的布局。
  3. 您可以通過調用LayoutInflater.from(getActivity())隨時獲取LayoutInflater.from(getActivity())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM