所以我有三个标签,其中两个标签我必须进行改装调用。
我试过调用onCreateView方法中有改进调用的方法。在onResponse方法中,我尝试通过收到的URL加载图像。但是当我调试我的应用程序时,即使在调用onResponse之前,onCreateView也会返回视图。
我应该在哪种方法中使用片段进行改装调用?
public class Tab3Fragment extends Fragment {
private ImageView trailer_thumbnail;
private static final String preImgUrl = "http://img.youtube.com/vi/";
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab3_fragment, container, false);
trailer_thumbnail = (ImageView) rootView.findViewById(R.id.trailer_thumbnail);
updateTrailer();
/*if( DetailsActivity.movieTrailerList.size() != 0 )
Picasso.with(getContext()).load(preImgUrl + DetailsActivity.movieTrailerList.get(0).getKey() + "/default.jpg").
placeholder(R.mipmap.ic_launcher).
error(R.mipmap.ic_launcher).
into(trailer_thumbnail);*/
return rootView;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void updateTrailer(){
final ProgressDialog mProgressDialog = new ProgressDialog(getContext());
mProgressDialog.setIndeterminate(true);
mProgressDialog.setMessage("Loading...");
mProgressDialog.show();
Retrofit retrofit = new Retrofit.Builder().
baseUrl(MainActivity.baseUrl).
addConverterFactory(GsonConverterFactory.create()).
build();
final RequestInterface requestInterface = retrofit.create(RequestInterface.class);
Call<MovieTrailerResponse> call1 = requestInterface.getMovieTrailers(list.get(index).getId(), MainActivity.apiKEy);
call1.enqueue(new Callback<MovieTrailerResponse>() {
@Override
public void onResponse(Call<MovieTrailerResponse> call, Response<MovieTrailerResponse> response) {
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
List<MovieTrailer> movieTrailerList = response.body().getResults();
Log.i("trailer", preImgUrl + movieTrailerList.get(0).getKey() + "/default.jpg");
if ( movieTrailerList.get(0).getSite() == "YouTube")
Picasso.with(getActivity()).load( preImgUrl + movieTrailerList.get(0).getKey() + "/default.jpg").
into(trailer_thumbnail);
}
@Override
public void onFailure(Call<MovieTrailerResponse> call, Throwable t) {
}
});
}
这是我的tab3片段类,当我调试应用程序时,即使在选择预告片选项卡并且在api调用接收数据之前返回视图之前,仍会调用onCreateView
。因此即使使用progressdialog,我也无法加载图像。事实上,当我选择tab2时会显示进度对话框。
答案 0 :(得分:1)
Retrofit
以异步方式运行,这意味着它与UI线程(主线程)分开运行。由于您正在等待Retrofit
的结果,该结果在不同的线程上运行,因此最佳的UI实践是运行ProgressDialog
直到Retrofit
获取URL。然后,您可以关闭ProgressDialog
并使用Picasso
渲染图像。您还可以在加载时使用占位符图像,使用毕加索使用onError案例:
Picasso.with(context)
.load(url)
.placeholder(R.drawable.user_placeholder)
.error(R.drawable.user_placeholder_error)
.into(imageView);
回答你的问题,从主线程等待网络呼叫取回响应真的是一个坏习惯。上述方式将是理想的。
此外,
我应该在哪种方法中使用片段进行改装调用?
您可以自由地从Retrofit
方法调用onCreateView()
来电,您需要等到收到回复。希望它有所帮助。
答案 1 :(得分:0)
您可以在 onViewCreated 方法中执行此操作,我假设您在onCreateView方法中正确查看注入,然后在OnViewCreated中您可以执行api调用并在onResponse的Retrofit调用中可以使用该数据