Android - 基于异步服务器响应在片段视图中设置数据

时间:2015-01-23 15:44:54

标签: android android-activity android-fragments android-asynctask android-lifecycle

我有如下的片段,其中onPostNetworkRequestWithCode()方法由代码的另一部分(App扩展应用程序类进行网络请求)回调,以绘制视图

由于片段创建链(onCreate(),onCreateView()等)在与重新绘制视图的onPostNetworkRequestWithCode()不同的线程中被调用,因此当onPostNetworkRequestWithCode()方法找不到时,我有一个竞争条件绘画的观点。如何让它等到视图创建完成后再继续发布?

public class MeStatsTableFragment extends Fragment implements HttpResponseHandlerWithResponseCode {

    private static final String LINKED_USER_ID = "linkedUserId";
    private Context mContext;

    public MeStatsTableFragment() {
        // Required empty public constructor
    }

    public static MeStatsTableFragment newInstance(long linkedUserId, Context context) {
        MeStatsTableFragment fragment = new MeStatsTableFragment();
        Bundle args = new Bundle();
        args.putLong(LINKED_USER_ID, linkedUserId);

        fragment.setArguments(args);
        fragment.mContext = context;
        return fragment;
    }


    /**
     * This is responsible for painting the chart after data is obtained by parent Me Fragment
     */
    @Override
    public void onPostNetworkRequestWithCode(HttpResponseCode responseCode) {

        long linkedUserId = getArguments().getLong(LINKED_USER_ID);
        MePageInfo m = App.getAppData().getMePageInfoById(linkedUserId);


        View v = getView();

        if (v == null) {
            Log.d("XXX", "Stats fragment Got stuck at view == null in Stats Fragment");
            // do nothing else, just return
        } else{


            v.findViewById(R.id.text_name).setText(m.name);
            // do other painting similarly with the view and the variable m



    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_me_stats_table, container, false);
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }


}

1 个答案:

答案 0 :(得分:0)

您可以使用greenrobot EventBus(https://github.com/greenrobot/EventBus) - 并在没有片段的情况下发帖。

以下是有关粘贴帖子和注册的更多信息 - https://github.com/greenrobot/EventBus/blob/master/HOWTO.md#sticky-events