我将 ListView 添加到 SwipeRefreshLayout。但是,onRefresh 方法不起作用。列表视图带有数据,我猜列表视图的滚动会阻止 onRefresh 工作。我正在使用一种在第一个项目可见时启用 swipeContainer 的方法。您能否检查我的代码并告诉我我做错了什么?
这是我的活动:
public class TimelineActivity extends Activity {
private SwipeRefreshLayout swipeContainer;
JSONObject jsonobject;
JSONObject jsonobj;
CityList list;
ArrayList<CityInfo> myList;
SharedPreferences sp;
JSONArray jArray = null;
JSONArray jResult = null;
Object info;
String resultmsg = null;
String json;
ListView theListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer);
// Setup refresh listener which triggers new data loading
swipeContainer.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh() {
// Your code to refresh the list here.
// Make sure you call swipeContainer.setRefreshing(false) when
// once the network request has completed successfully.
Log.i("refresh","refreshing");
new DownloadJSON().execute();
}
});
ViewGroup vg = (ViewGroup) findViewById(R.id.mainlayoutarea);
ViewGroup.inflate(TimelineActivity.this, R.layout.city_list, vg);
setContentView(R.layout.city_list);
theListView = (ListView) findViewById(R.id.cityList);
theListView.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
boolean enable = false;
if(theListView != null && theListView.getChildCount() > 0){
// check if the first item of the list is visible
boolean firstItemVisible = theListView.getFirstVisiblePosition() == 0;
// check if the top of the first item is visible
boolean topOfFirstItemVisible = theListView.getChildAt(0).getTop() == 0;
// enabling or disabling the refresh layout
enable = firstItemVisible && topOfFirstItemVisible;
}
swipeContainer.setEnabled(enable);
}
});
swipeContainer.setColorSchemeResources(android.R.color.holo_blue_light,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
new DownloadJSON().execute();
}