myViewPager2.setUserInputEnabled(false);// SAMPLE CODE to disable swiping in viewpager2
myViewPager2.setUserInputEnabled(true);//SAMPLE CODE to enable swiping in viewpager2
class FirstFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_first, container, false)
}
companion object{
fun newInstance() = FirstFragment()
}
}
ViewPagerAdapter.kt
class ViewPagerAdapter(fa:FragmentActivity, private val fragments:ArrayList<Fragment>): FragmentStateAdapter(fa) {
override fun getItemCount(): Int = fragments.size
override fun createFragment(position: Int): Fragment = fragments[position]
}
public class CustomFragmentStateAdapter extends FragmentStateAdapter {
private ArrayList<Fragment> arrayList = new ArrayList<>();
public CustomFragmentStateAdapter (FragmentActivity fa) {
super(fa);
}
public void addFragment(Fragment fragment) {
arrayList.add(fragment);
}
@Override
public int getItemCount() {
return arrayList.size();
}
@NonNull
@Override
public Fragment createFragment(int position) {
// return your fragment that corresponds to this 'position'
return arrayList.get(position);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report);
ButterKnife.bind(this);
actionBarTitleId.setText(R.string.reports);
viewPager.setAdapter(new ViewPagerAdapter(this));
new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> {
switch (position) {
case 0:
tab.setText(R.string.financial_duty_str);
break;
case 1:
tab.setText(R.string.financial_unpaid_str);
break;
case 2:
tab.setText(R.string.financial_paid_str);
break;
}
}).attach();
}
ViewPager2适配器:
public class ViewPagerAdapter extends FragmentStateAdapter {
public ViewPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
super(fragmentActivity);
}
@NonNull
@Override
public Fragment createFragment(int position) {
switch (position) {
case 0:
return new FinancialFragment();
case 1:
return new FinancialUnPaidFragment();
case 2:
return new FinancialPaidFragment();
default:
return null;
}
}
@Override
public int getItemCount() {
return 3;
}
private val fragmentTransactionCallback =
object : FragmentStateAdapter.FragmentTransactionCallback() {
override fun onFragmentMaxLifecyclePreUpdated(
fragment: Fragment,
maxLifecycleState: Lifecycle.State
) = if (maxLifecycleState == Lifecycle.State.RESUMED) {
// This fragment is becoming the active Fragment - set it to
// the primary navigation fragment in the OnPostEventListener
OnPostEventListener {
fragment.parentFragmentManager.commitNow {
setPrimaryNavigationFragment(fragment)
}
}
} else {
super.onFragmentMaxLifecyclePreUpdated(fragment, maxLifecycleState)
}
}
init {
// Add a FragmentTransactionCallback to handle changing
// the primary navigation fragment
registerFragmentTransactionCallback(fragmentTransactionCallback)
}
@AndroidEntryPoint
class RecipeDetailsFragment : Fragment(R.layout.fragment_recipe_details) {
private val viewModel: RecipeItemViewModel by viewModels()
private val viewBinding: FragmentRecipeDetailsBinding by viewBinding()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
bindRecipeData(//object of data that is to be desplayed)
}
private fun bindRecipeData(recipeDetailedInfo: RecipeDetailedInfo?) {
recipeDetailedInfo?.let {
with(viewBinding) {
viewPager2.adapter = ViewPagerAdapter(it.images)
viewPager2.setPageTransformer(ZoomOutPageTransformer())
lifecycleScope.launchWhenCreated {
delay(500)
viewPager2.setCurrentItem(if (it.images.size >= 2) 1 else 0, true)
}
}
}
}....
在片段中,我创建适配器的对象,并直接发送包含图像 URL 的字符串列表
这是视图页面适配器,它基本上是一个普通的回收视图适配器
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.blogspot.soyamr.recipes2.databinding.ImageviewBinding
import com.squareup.picasso.Picasso
class ViewPagerAdapter(private val images: List<String>) :
RecyclerView.Adapter<ViewPagerAdapter.ImageViewHolder>() {
class ImageViewHolder(private val imageViewBinding: ImageviewBinding) :
RecyclerView.ViewHolder(imageViewBinding.root) {
fun bind(imageLink: String) {
Picasso.get().load(imageLink).into(imageViewBinding.root)
}
companion object {
fun from(parent: ViewGroup): ImageViewHolder {
val itemBinding =
ImageviewBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ImageViewHolder(itemBinding)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder {
return ImageViewHolder.from(parent)
}
override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {
holder.bind(images[position])
}
override fun getItemCount(): Int = images.size
}
public class MainToolsAdapter extends FragmentStateAdapter
{
// The quantity of tab is fixed
private static final int FRAGMENT_COUNT = 2;
// Titles for each tab
private final String[] titles = new String[FRAGMENT_COUNT];
public MainToolsAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle, Context context)
{
super(fragmentManager, lifecycle);
// Load titles for tab from resourses
titles[0] = context.getResources().getString(R.string.tab_1);
titles[1] = context.getResources().getString(R.string.tab_2);
}
@NonNull
@Override
public Fragment createFragment(int position)
{
// Create fragments according to position
if(position == 0)
{
return new FragmentTabOne();
}
return new FragmentTabTwo();
}
@Override
public int getItemCount()
{
return FRAGMENT_COUNT;
}
public String getItemTitle(int position)
{
if(position == 0)
{
return titles[0];
}
return titles[1];
}
}
主要活动:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create adapter for ViewPager
mainToolsAdapter = new MainToolsAdapter(getSupportFragmentManager(), getLifecycle(), this);
// Set adapter to the ViewPager
viewPager = findViewById(R.id.mainViewPager);
viewPager.setAdapter(mainToolsAdapter);
tabLayout = findViewById(R.id.mainTabLayout);
// Create the TabLayoutMediator to asociate ViewPager2 to TabLayout
TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPager, true, new TabLayoutMediator.TabConfigurationStrategy()
{
@Override
public void onConfigureTab(@NonNull TabLayout.Tab tab, int position)
{
// When a tab is created this is called, then we can set tab properties, in this case the text
tab.setText(mainToolsAdapter.getItemTitle(position));
}
});
// After configure we need to realice attach then Tab and ViewPager2 are asociated
tabLayoutMediator.attach();
}
private final ViewPager2.OnPageChangeCallback onPageChangeListener = new ViewPager2.OnPageChangeCallback() {
/**
* This method will be invoked when the current page is scrolled, either as part
* of a programmatically initiated smooth scroll or a user initiated touch scroll.
* @param position Position index of the first page currently being displayed.
* Page position+1 will be visible if positionOffset is nonzero.
* @param positionOffset Value from [0, 1) indicating the offset from the page at position.
* @param positionOffsetPixels Value in pixels indicating the offset from position.
*/
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
/**
* This method will be invoked when a new page becomes selected.
* Animation is not necessarily complete.
* @param position Position index of the first page currently being displayed.
* Page position+1 will be visible if positionOffset is nonzero.
*/
@Override
public void onPageSelected (int position) {
super.onPageSelected(position);
if (position == 2) { // SomeFragment
Log.d(LOG_TAG, "ViewPager2.onPageSelected( " + position + " )");
SomePagerAdapter adapter = (SomePagerAdapter) viewpager.getAdapter();
if (adapter != null) {
SomeFragment fragment = (SomeFragment) adapter.getItem(position);
fragment.onLateInit();
}
}
}
};
class ScreenSlidePageAdapter(val fragment: Fragment): FragmentStateAdapter(fragment) {
val fragments = listOf(WalkThroughFragment(), PermissionsFragment(), DatastoreFragment())
override fun getItemCount(): Int {
return fragments.size
}
override fun createFragment(position: Int): Fragment {
return fragments[position]
}
}
ViewPager2的转换-可选
class ZoomOutPageTransformer : ViewPager2.PageTransformer {
override fun transformPage(view: View, position: Float) {
view.apply {
val pageWidth = width
val pageHeight = height
when {
position < -1 -> { // [-Infinity,-1)
// This page is way off-screen to the left.
alpha = 0f
}
position <= 1 -> { // [-1,1]
// Modify the default slide transition to shrink the page as well
val scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position))
val vertMargin = pageHeight * (1 - scaleFactor) / 2
val horzMargin = pageWidth * (1 - scaleFactor) / 2
translationX = if (position < 0) {
horzMargin - vertMargin / 2
} else {
horzMargin + vertMargin / 2
}
// Scale the page down (between MIN_SCALE and 1)
scaleX = scaleFactor
scaleY = scaleFactor
// Fade the page relative to its size.
alpha = (MIN_ALPHA +
(((scaleFactor - MIN_SCALE) / (1 - MIN_SCALE)) * (1 - MIN_ALPHA)))
}
else -> { // (1,+Infinity]
// This page is way off-screen to the right.
alpha = 0f
}
}
}
}