使用 Viewpager2 和 Kotlin 在片段之间滑动

Sliding between fragments using Viewpager2 and Kotlin

我有一个用 Java 编写的旧项目,可以在三个不同的片段之间水平滑动,它们在主 activity 上有说明。它运行完美。

public class MainActivity extends AppCompatActivity {
ViewPager pager;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    pager = findViewById(R.id.theViewPagerInTheMainActivity);
    pager.setOffscreenPageLimit(3);
    PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());

    Frag_A aFrag = new Frag_A();
    adapter.addItem(aFrag);
    Frag_B bFrag = new Frag_B();
    adapter.addItem(bFrag);
    Frag_C cFrag = new Frag_C();
    adapter.addItem(cFrag);

    pager.setAdapter(adapter);
    pager.setCurrentItem(1);
  }

  class PagerAdapter extends FragmentStatePagerAdapter {
    ArrayList<Fragment> items = new ArrayList<Fragment>();
    public PagerAdapter(FragmentManager fragManager) {
        super(fragManager);
    }
    public void addItem(Fragment item) {
        items.add(item);
    }
    @Override
    public Fragment getItem(int position) {
        return items.get(position);
    }
    @Override
    public int getCount() {
        return items.size();
        }
    }
}

每三个不同的片段,后跟可以正常工作的不同代码,开头为:

public class Frag_A extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.frag_a, container, false);
    }
}

Frag_B 和 frag_b 布局,Frag_C 和 frag_c 布局也是如此。

我现在又在做这一切,但在 Kotlin 中并使用 ViewPager2。我没有以编程方式制作任何片段,我希望他们的三个 ID 都写在主 activity 上。当然,直接在 Android Studio 中转换代码是行不通的,数小时的搜索也无法满足我的需求。根据我的浅薄理解,从一个预制片段创建不同颜色的片段似乎并不适合我的项目,所有片段都以红色下划线结束。不导入.v4配套库能做吗?

自己解决了!

class MainActivity : FragmentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val adapter = DatPagerAdapter(this)
    val fragsList = listOf(Frag_A(), Frag_B(), Frag_C())
    adapter.fragsListHere.addAll(fragsList)
    theVP2InTheMainActivity.adapter = adapter
    theVP2InTheMainActivity.setCurrentItem(1)
  }
  class DatPagerAdapter(fragactivity: FragmentActivity) : FragmentStateAdapter(fragactivity) {
    val fragsListHere = mutableListOf<Fragment>()
    override fun getItemCount():Int = fragListHere.size
    override fun createFragment(position: Int): Fragment = fragListHere[position]
  }
}

因为 FragmentPagerAdapter 已被破坏。我将它切换到 FragmentStateAdapter(FragmentActivity fragmentActivity) 与 ViewPager2

一起工作

我的 ViewPagerAdapter :

``` 
    class ViewPagerAdapter(fragmentActivity: FragmentActivity): 
    FragmentStateAdapter(fragmentActivity){

    override fun getItemCount(): Int {
        return 3
    }

    override fun createFragment(position: Int): Fragment {
        return when(position){
            0 -> {
                HomeFragment()
            }
            1 -> {
                HomeFragment2()
            }
            2 -> {
                HomeFragment3()
            }
            else -> {
                throw Resources.NotFoundException("Position Not Found")
            }
        }
    }
}
```

我的Activity:

    class MainActivity5 : AppCompatActivity() {
    
        private lateinit var binding: ActivityMain5Binding
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            binding = ActivityMain5Binding.inflate(layoutInflater)
            val view = binding.root
            setContentView(view)
    
            binding.viewpager.adapter = ViewPagerAdapter(this)
    
        }
        // If the user is currently looking at the first step, allow the system to handle the
        // Back button. This calls finish() on this activity and pops the back stack.

    override fun onBackPressed() {
        if (binding.viewpager.currentItem == 0) {
            super.onBackPressed()
        } else {
            // Otherwise, select the previous step.
            binding.viewpager.currentItem = binding.viewpager.currentItem - 1
        }
    }
    }

谢谢提问!! 注意:我使用绑定来替换 findViewById