代码部分:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <androidx.viewpager.widget.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent" tools:layout_editor_absoluteX="1dp" tools:layout_editor_absoluteY="1dp" /> </androidx.constraintlayout.widget.ConstraintLayout>
a1.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="第一个界面" /> </LinearLayout>
a2.xml a3.xml 和 a1 相同
MainActivity.java
package com.example.viewpagertest; import androidx.appcompat.app.AppCompatActivity; import androidx.viewpager.widget.ViewPager; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private ViewPager viewPager; private List<View> views; private MyNewAdapter myNewAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewPager = findViewById(R.id.viewpager); views = new ArrayList<View>(); LayoutInflater layoutInflater = LayoutInflater.from(getApplicationContext()); View view1 = layoutInflater.inflate(R.layout.a1,null); View view2 = layoutInflater.inflate(R.layout.a2,null); View view3 = layoutInflater.inflate(R.layout.a3,null); views.add(view1); views.add(view2); views.add(view3); myNewAdapter = new MyNewAdapter(views); viewPager.setAdapter(myNewAdapter); } }
MyNewAdapter.java
package com.example.viewpagertest; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager; import java.util.List; public class MyNewAdapter extends PagerAdapter { List<View> views; public MyNewAdapter(List<View> views) { this.views = views; } @Override public int getCount() { return views.size(); } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view==object; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { ((ViewPager)container).removeView(views.get(position)); } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { ((ViewPager)container).addView(views.get(position)); return views.get(position); } }
效果图:
左右滑动屏幕