我正在使用接口将对象列表从活动发送到片段。 这是我的界面:
public interface CurrenciesSync {
void syncCurrencies(List<CurrencyModel> currencies);
}
这是我调用接口方法设置数据的方式:
public void getCurrencies(){
APIInterface apiInterface = APIClient.getClient().create(APIInterface.class);
Call<GetCurrenciesModel> call = apiInterface.getCurrencies();
call.enqueue(new Callback<GetCurrenciesModel>() {
@Override
public void onResponse(Call<GetCurrenciesModel> call, Response<GetCurrenciesModel> response) {
if(response.isSuccessful()) {
if (response.body().getStatus() == true){
currencies = new ArrayList<CurrencyModel>();
for (int i = 0 ; i< response.body().getCurrencies().size(); i++){
currencies.add(response.body().getCurrencies().get(i));
}
new FeesFragment();
CurrenciesSync currenciesSync = new CurrenciesSync() {
@Override
public void syncCurrencies(List<CurrencyModel> currencies) {
// your code
}
};
currenciesSync.syncCurrencies(currencies);
}
}
@Override
public void onFailure(Call<GetCurrenciesModel> call, Throwable t){
}
});
}
这是我用来获取片段数据的方法:
@Override
public void syncCurrencies(List<CurrencyModel> currencies) {
List<FeeItemModel> currency = new ArrayList<>();
for (int i= 0 ; i < currencies.size() ; i++){
currency.add(
new FeeItemModel(
currencies.get(i).getSomething(),
currencies.get(i).getSomething(),
currencies.get(i).getSomething(),
currencies.get(i).getSomething(),
currencies.get(i).getSomething())
); }
CurrenciesAdaptor currenciesAdaptor = new CurrenciesAdaptor(getContext(),currency);
RecyclerView.setAdapter(currenciesAdaptor);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
RecyclerView.setLayoutManager(linearLayoutManager);
RecyclerView.setItemAnimator(new DefaultItemAnimator());
}
,但是以下方法无法运行。 注意:片段也是在myActivity的另一个地方创建的,即使我试图创建一个新的片段实例以确保它被创建,也没有任何改变。
答案 0 :(得分:0)
似乎通过接口对象在活动类中设置数据时,片段可能未附加到活动中,这似乎不是将数据从活动发送到片段的正确方法,因为这可能不是每次。
To use the recommended method to send data from activity to fragment use this link:-