ViewPager2
和RecyclerView
结合SnapHelper
来实现。以下是一个简单的示例代码:,,``java,import android.os.Bundle;,import androidx.annotation.Nullable;,import androidx.appcompat.app.AppCompatActivity;,import androidx.recyclerview.widget.LinearSnapHelper;,import androidx.recyclerview.widget.RecyclerView;,import androidx.viewpager2.widget.ViewPager2;,,public class MainActivity extends AppCompatActivity {, private ViewPager2 viewPager;, private RecyclerView recyclerView;,, @Override, protected void onCreate(@Nullable Bundle savedInstanceState) {, super.onCreate(savedInstanceState);, setContentView(R.layout.activity_main);,, viewPager = findViewById(R.id.viewPager);, recyclerView = findViewById(R.id.recyclerView);,, // 设置ViewPager2的适配器, viewPager.setAdapter(new MyPagerAdapter());,, // 设置RecyclerView的布局管理器和适配器, recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));, recyclerView.setAdapter(new MyRecyclerAdapter());,, // 添加SnapHelper以实现自动对齐效果, LinearSnapHelper snapHelper = new LinearSnapHelper();, snapHelper.attachToRecyclerView(recyclerView);, },},
``,,这个示例展示了如何在Android应用中实现基本的双向滑动特效。你可以根据需要进一步自定义和扩展功能。Powered By Z-BlogPHP 1.7.3