RecentNewsFragment.java
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final String TAG = "MainPageActivity";
final RecyclerView rvNewsArticle;
final SwipeRefreshLayout swipeRefreshLayout;
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_recent_news, container, false);
rvNewsArticle = (RecyclerView) view.findViewById(R.id.rvNewsArticle);
rvNewsArticle.setHasFixedSize(true);
LinearLayoutManager manager = new LinearLayoutManager(getActivity());
rvNewsArticle.setLayoutManager(manager);
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefresh);
swipeRefreshLayout.setColorSchemeResources(R.color.primaryColor, R.color.primaryTextColor, R.color.secondaryColor);
String url = "http://192.168.0.29/theflare/app/news.php";
StringRequest stringRequest = new StringRequest(Request.Method.GET,
url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, response);
ArrayList<News> newsList = new JsonConverter<News>()
.toArrayList(response, News.class);
final NewsArticleAdapter adapter = new NewsArticleAdapter(getActivity(), newsList);
rvNewsArticle.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
rvNewsArticle.setAdapter(adapter);
swipeRefreshLayout.setRefreshing(false);
}
}, 2500);
}
});
}
}
);
MySingleton.getInstance(getActivity()).addToRequestQueue(stringRequest);
return view;
}
如您所见,这是我为CardView
构建的代码。不幸的是,我的SwipeRefreshLayout
不起作用。 (它有效,但只有动画,并且不刷新视图。)我是否将setOnRefreshListener
放在错误的地方或者我在这里丢失了什么?谢谢你的帮助。
答案 0 :(得分:1)
你的回调方法在错误的地方。您应该使用onRefresh()
方法创建新请求,而不是相反。
private static final String NEWS_URL = "http://192.168.0.29/theflare/app/news.php";
private SwipeRefreshLayout mSwipeRefreshLayout;
private RecyclerView mRecyclerView;
@Override
public view onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// ...
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
loadNews();
}
});
return view;
}
private void loadNews() {
StringRequest request = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
ArrayList<News> newsList = new JsonConverter<News>().toArrayList(response, News.class);
NewsArticleAdapter adapter = new NewsArticleAdapter(getActivity(), newsList);
mRecyclerView.setAdapter(adapter);
mSwipeRefreshLayout.setRefreshing(false);
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}