我可以从活动中发送凌空请求并使用片段中的响应



我正在从活动中发送凌空请求。我想以两个片段访问结果。text1 to text6在一个片段中,并保留在另一个片段中的pojo数组或两个响应中,我需要从两个片段中发送两个请求?以下是依据

{ " text1":" lion_1", " text2":" lion_2", " text3":" lion_3", " text4":" lion_4", " text5":" lion_5", " text6":" lion_6", " pojo":[[ { "中":" lion_1.jpe", "名称":" Lion_1" },, { "中":" lion_2.jpe", "名称":" Lion_2" },, { "中":" lion_3.jpe", "名称":" Lion_3" },, { "中":" lion_4.jpe", "名称":" Lion_4" },, { "中":" lion_5.jpe", "名称":" Lion_5" },, { "中":" lion_6.jpe", "名称":" Lion_6" } 这是给出的}

是的,您可以做到这一点。

这是您可以通过主要活动传达回应的方式。

MainActivity

public class MainActivity extends AppCompatActivity {
    FragOne fragOne;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        fragOne = new FragOne();
        //add fragment

    }
    void onResponse(String response){
        fragOne.getNetworkResponse(response);
    }
}

fragment

class FragOne extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ...
    }
    public void getNetworkResponse(string responce){
        //process response here.
    }
}

是的,这是可能的。首先,您需要在背景中解析JSON响应并将其保存在活动中。Web呼叫和解析完成后,请通知有关新数据的片段。您可以创建一些通过FragmentsM在活动中实现特定数据的接口。每个片段都会将活动投入到该接口并获得所需的数据(如果有的话)。为了告诉fragment,这是可用的新数据,您可以创建界面并在新数据中实现它,或者每次创建新的fragment实例,然后从活动中获取数据

这里的答案始终等待请求完成,然后继续进行片段以及耦合活动和片段

但是,我会使片段的活动分离。

imo我想将请求添加到队列形式的任何地方,并在任何地方接收回复,而没有任何地方知道自己或传递数据。使用rxjava并根据请求标签观察响应来实现此目标的一种方法。

我创建了一个基于凌空的图书馆JUS,您可以在其中插入RXJAVA并轻松实现此行为:

在一个片段中:

//Calls the API (adds requests to the queue)     
MyJus.intructablesApi().list(20,0, Instructables.SORT_RECENT,"id");
//starts the other fragment
frag = InstructablesListFragment.newInstance();
fragmentManager.beginTransaction()
            .replace(R.id.container, frag)
            .commit();

在另一个片段中:

     RecyclerAdapter recyclerAdapter = new RxAdapter(
MyJus.hub().get(REQ_LIST).map(o -> ((ResultEvent) o).response));

集线器从所有请求中收集所有响应并通过概念安排它们。

您可以在GitHub中检查完整示例: