要解决Android ViewPager2无法动态包裹不同大小片段的高度的问题,你可以使用以下代码示例中的解决方案:
implementation 'androidx.viewpager2:viewpager2:1.0.0'
public class MyFragmentPagerAdapter extends RecyclerView.Adapter {
private List fragments;
public MyFragmentPagerAdapter(List fragments) {
this.fragments = fragments;
}
@NonNull
@Override
public FragmentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_item, parent, false);
return new FragmentViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull FragmentViewHolder holder, int position) {
Fragment fragment = fragments.get(position);
FragmentTransaction transaction = ((FragmentActivity) holder.itemView.getContext()).getSupportFragmentManager().beginTransaction();
transaction.replace(holder.itemView.getId(), fragment).commit();
}
@Override
public int getItemCount() {
return fragments.size();
}
}
class FragmentViewHolder extends RecyclerView.ViewHolder {
public FragmentViewHolder(@NonNull View itemView) {
super(itemView);
}
}
ViewPager2 viewPager = findViewById(R.id.viewPager);
List fragments = new ArrayList<>();
// 添加你的片段到fragments列表中
MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(fragments);
viewPager.setAdapter(adapter);
通过这种方式,ViewPager2将会动态包裹不同大小的片段高度。