我正在尝试以编程方式添加刷卡刷新,但它无法正常工作。拉动刷新没有动作。这有什么不对吗?
ListView listView = (ListView) findViewById(R.id.listView);
List<String> values = new ArrayList<>();
values.add("Hello");
values.add("hi");
values.add("Hello");
values.add("hi");
values.add("Hello");
values.add("hi");
values.add("Hello");
values.add("hi");
values.add("Hello");
values.add("hi");
values.add("Hello");
values.add("hi");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
listView.setAdapter(adapter);
SwipeRefreshLayout swipeRefreshLayout = new SwipeRefreshLayout(this);
SwipeRefreshLayout.LayoutParams swipeRefreshLayoutParams = new SwipeRefreshLayout.LayoutParams(SwipeRefreshLayout.LayoutParams.MATCH_PARENT, SwipeRefreshLayout.LayoutParams.WRAP_CONTENT);
swipeRefreshLayout.setLayoutParams(swipeRefreshLayoutParams);
swipeRefreshLayout.setBackgroundColor(Color.RED);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
Log.d(TAG, "Pulled");
}
});
ViewGroup r = (ViewGroup) listView.getParent();
r.addView(swipeRefreshLayout);
答案 0 :(得分:3)
视图的当前层次结构为:
ParentLayout - &gt; ListView。
但我们想要的是:
ParentLayout - &gt; SwipeToRefresh - &gt;的ListView 强>
这是因为一个视图不能有2个父母。
因此,
final SwipeRefreshLayout swipeLayout = new SwipeRefreshLayout(context);
((ViewGroup) listView.getParent()).addView(swipeLayout);
((ViewGroup) listView.getParent()).removeView(listView);
swipeLayout.addView(listView);
请务必将onRefresh侦听器附加到swipeRefresh布局。