implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha02'
xml : 리사이클러 뷰를 swiperfreshlayout 로 감싼다
사용예시
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private SwipeRefreshLayout swipeRefreshLayout;
private ListView listView;
private List<Integer> items;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeRefreshLayout = findViewById(R.id.swipe_refresh);
listView = findViewById(R.id.list_view);
items = new ArrayList<>();
//초기값 설정
items.add(10);
items.add(20);
items.add(30);
items.add(40);
items.add(50);
items.add(60);
items.add(70);
final ArrayAdapter<Integer> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_red_dark);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
insertData();
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
});
}
public void insertData(){
Random r = new Random();
int ranNum = r.nextInt(100)+1;
items.add(ranNum);
Collections.sort(items);
}
}
xml
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/swipeLy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:layout_marginTop="10dp">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rvPosts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
java
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
Log.d(TAG, "onCreateView: context " + getContext());
swipeRefreshLayout = view.findViewById(R.id.swipeLy);
rvKeywords = (RecyclerView) view.findViewById(R.id.rvKeywords);
rvPosts = (RecyclerView) view.findViewById(R.id.rvPosts);
initAdapter();
initSetting();
initData();
return view;
}
@Override
public void initSetting() {
swipeRefreshLayout.setColorSchemeResources(R.color.green);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
Log.d(TAG, "onRefresh: ");
initData();
swipeRefreshLayout.setRefreshing(false);
}
});
데이터 초기화를 onCreate 에서 하고 스와이프 쓰면 일케 됨