我创建了一个应用程序,用于从XML文件获取RSS Feed,并将其显示在卡片视图中的recyclerview中。我想实现拉动以刷新以加载数据。 该方法到底应该在哪里? 我的主要活动:
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
//Call Read rss asyntask to fetch rss
try {
ReadRss readRss = new ReadRss(this, recyclerView);
readRss.execute();
}catch (Exception e) {
Toast.makeText(getApplicationContext(), "There's a problem", Toast.LENGTH_LONG);
}
}
}
这是ReadRss类:
public class ReadRss extends AsyncTask<Void, Void, Void> {
Context context;
String address = "http://karary-001-site1.htempurl.com/XMLFile1.xml";
ProgressDialog progressDialog;
ArrayList<FeedItem> feedItems;
RecyclerView recyclerView;
URL url;
public ReadRss(Context context, RecyclerView recyclerView) {
this.recyclerView = recyclerView;
this.context = context;
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("loading....");
}
//before fetching of rss statrs show progress to user
@Override
protected void onPreExecute() {
progressDialog.show();
super.onPreExecute();
}
//This method will execute in background so in this method download rss feeds
@Override
protected Void doInBackground(Void... params) {
//call process xml method to process document we downloaded from getData() method
ProcessXml(Getdata());
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
FeedsAdapter adapter = new FeedsAdapter(context, feedItems);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.addItemDecoration(new VerticalSpace(20));
recyclerView.setAdapter(adapter);
}
pullToRefresh方法:
final SwipeRefreshLayout pullToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
//refresh code
pullToRefresh.setRefreshing(false);
}
});
该方法应该在哪里?
答案 0 :(得分:0)
首先设置pullToRefresh.setRefreshing(true);如果不起作用,请尝试下面的代码
pullToRefresh.post(new Runnable() {
@Override
public void run() {
pullToRefresh.setRefreshing(true);
}
});
答案 1 :(得分:0)
这是您可以做的
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
//refresh code
ReadRss readRss = new ReadRss(this, recyclerView);
readRss.execute();
}
});
,然后在onPostExeceute()
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
pullToRefresh.setRefreshing(false); // in case of pullToRefresh
FeedsAdapter adapter = new FeedsAdapter(context, feedItems);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.addItemDecoration(new VerticalSpace(20));
recyclerView.setAdapter(adapter);
}
希望这会有所帮助