在Android開發中,使用SmartRefreshLayout可以幫助我們輕松實現下拉刷新和上拉加載更多功能。為了使SmartRefreshLayout適配不同屏幕尺寸,我們需要考慮以下幾點:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
<com.scwang.smartrefresh.layout.SmartRefreshLayout
android:id="@+id/smartRefreshLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
</com.scwang.smartrefresh.layout.SmartRefreshLayout>
RecyclerView recyclerView = findViewById(R.id.recyclerView);
SmartRefreshLayout smartRefreshLayout = findViewById(R.id.smartRefreshLayout);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
MyAdapter adapter = new MyAdapter();
recyclerView.setAdapter(adapter);
smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh(RefreshLayout refreshLayout) {
// 在這里執行刷新操作
refreshLayout.finishRefreshing();
}
});
smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
@Override
public void onLoadMore(RefreshLayout refreshLayout) {
// 在這里執行加載更多操作
refreshLayout.finishLoadMore();
}
});
public static int getScreenHeight(Context context) {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics displayMetrics = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(displayMetrics);
return displayMetrics.heightPixels;
}
然后,在Activity或Fragment的onCreate
方法中設置SmartRefreshLayout的高度:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int screenHeight = getScreenHeight(this);
ViewGroup.LayoutParams layoutParams = smartRefreshLayout.getLayoutParams();
layoutParams.height = screenHeight - getSupportActionBar().getHeight() - (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48, getResources().getDisplayMetrics());
smartRefreshLayout.setLayoutParams(layoutParams);
}
這樣,SmartRefreshLayout就能根據屏幕尺寸自動調整高度,從而實現不同屏幕尺寸的適配。