如何在android中提供列表视图Pull Down to Refresh功能

时间:2013-06-12 12:36:46

标签: android

如何在android中创建下拉刷新列表?

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pull_to_refresh);

    // Set a listener to be invoked when the list should be refreshed.
    ((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {
        @Override
        public void onRefresh() {
            // Do work to refresh the list here.
            new GetDataTask().execute();
        }
    });

    mListItems = new LinkedList<String>();
    mListItems.addAll(Arrays.asList(mStrings));

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, mListItems);

    setListAdapter(adapter);
}`

1 个答案:

答案 0 :(得分:3)

这不是Android设计模式。但是,this优秀的库可让您轻松完成。看看这些例子。

希望我帮助过。

编辑 - 2015年12月12日 - 无视先前的陈述:

现在这是Android上的SDK完全支持的设计模式。

这非常简单,您需要使用SwipeRefreshLayout作为列表的父视图(或者您可能想要刷新的其他数据)。您可以将任何视图作为子视图放置,它将为该视图创建“Pull-To-Refresh”动画。

此后,您只需要实现SwipeRefreshLayout.OnRefreshListener来处理实际数据刷新的网络代码:

public class MainActivity extends FragmentActivity implements OnRefreshListener {

private SwipeRefreshLayout _pullToRefreshLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_main);

    _pullToRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_layout);
    _pullToRefreshLayout.setOnRefreshListener(this);

    super.onCreate(savedInstanceState);
}

@Override
public void onRefresh() {
    //When this is called, your view has a little loader showing to show the user that a network call is in progress
    Log.i("SO17065814", "Starting refresh...");

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            mSwipeRefreshLayout.setRefreshing(false); //This stops the refresh animation
            Log.i("SO17065814", "Ending refresh...");
        }
    }, 5000);
}

}