我有一个ViewPager,其中包含动态数量的片段。当用户在特定片段中输入数据并按下“发送”按钮时,活动中的方法会将输入的数据发送到服务器,然后活动接收响应。如何将接收到的数据正确发送到特定片段?非常感谢你!
片段:
public class ViewPagerFragment extends Fragment {
private TextView someText;
private Button sendTextButton;
private int pageId;
...
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_fragment, container, false);
someText = view.findViewById(R.id.someText);
sendTextButton = view.findViewById(R.id.sendTextButton);
sendTextButton.setOnClickListener(v -> {
((MyListener)getActivity()).onSend(pageId, someText);
});
return view;
}
...
}
活动分类:
public class TestActivity extends AppCompatActivity implements MyListener {
private MyViewModel myViewModel;
...
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
...
myViewModel = ViewModelProviders.of(this, new ViewModelFactory(MyRepository.getInstance())).get(MyViewModel.class);
myViewModel.sendResultResource().observe(this, data -> {
switch (data.status) {
case SUCCESS: {
// how to return the result to the fragment?
break;
}
case LOADING: {
setLoading(true);
break;
}
case ERROR: {
showError(data.message);
break;
}
}
});
}
@Override
public void onSend(int pageId, String text) {
myViewModel.sendAnswer(problemId, answers);
}
}
...
PagerAdapter:
public class MyPagerAdapter extends FragmentPagerAdapter {
private List<Data> dataList;
public MyPagerAdapter(FragmentManager fragmentManager, List<Data> dataList) {
super(fragmentManager);
this.dataList = dataList;
}
@Override
public int getCount() {
return dataList.size();
}
@Override
public MyFragment getItem(int position) {
return MyFragment.newInstance(position, dataList.get(position));
}
}
答案 0 :(得分:0)
将其写在捆绑包中怎么办?您如何看待?