MainActivity
package a.b.c.viewpager;
import android.os.Bundle; import android.view.LayoutInflater; import android.view.View;
import androidx.activity.EdgeToEdge; import androidx.appcompat.app.AppCompatActivity; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat; import androidx.viewpager.widget.ViewPager;
import java.util.ArrayList; import java.util.List;
public class MainActivity extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
LayoutInflater lf = getLayoutInflater().from(this); View view1 = lf.inflate(R.layout.layout1,null); View view2 = lf.inflate(R.layout.layout2,null); View view3 = lf.inflate(R.layout.layout3,null);
List<View> viewList = new ArrayList<>(); viewList.add(view1); viewList.add(view2); viewList.add(view3);
ViewPager viewPager = findViewById(R.id.vp); MyAdapter myAdapter = new MyAdapter(viewList); viewPager.setAdapter(myAdapter); } }
myAdapter package a.b.c.viewpager;
import android.view.View; import android.view.ViewGroup;
import androidx.annotation.NonNull; import androidx.viewpager.widget.PagerAdapter;
import java.util.List;
public class MyAdapter extends PagerAdapter {
private List<View> mListView;
@NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { container.addView(mListView.get(position),0);
return mListView.get(position); }
public MyAdapter(List<View> mListView){ this.mListView = mListView; }
@Override public int getCount() { return mListView.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) { container.removeView(mListView.get(position)); } }
|