View Pager
final androidx.viewpager.widget.ViewPager viewPager = new androidx.viewpager.widget.ViewPager(this);
viewPager.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
viewPager.setBackgroundColor(Color.BLACK);
MyPagerAdapter adapter = new MyPagerAdapter();
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(0);
linear1.addView(viewPager);
viewPager.addOnPageChangeListener(new androidx.viewpager.widget.ViewPager.OnPageChangeListener() { public void onPageSelected(int position) {
View noview = (View) viewPager.findViewWithTag("myview" + viewPager.getCurrentItem());
if (position == 1) {
Button bt = (Button) noview.findViewById(R.id.button1);
bt.setOnClickListener(new OnClickListener() { public void onClick(View v) {viewPager.setCurrentItem(0);} });
}
if (position == 3) {
TextView tt = (TextView) noview.findViewById(R.id.textview2);
tt.setTextIsSelectable(true);
tt.setText("Aan Gabriel");
}
}
@Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }
@Override public void onPageScrollStateChanged(int state) { }
});
}
private class MyPagerAdapter extends androidx.viewpager.widget.PagerAdapter {
public int getCount() {
return 4;
}
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position) {
case 0:
resId = R.layout.left;
break;
case 1:
resId = R.layout.farleft;
break;
case 2:
resId = R.layout.middle;
break;
case 3:
resId = R.layout.right;
break;
}
View view = inflater.inflate(resId, null);
((androidx.viewpager.widget.ViewPager)collection).addView(view, 0);
view.setTag("myview" + position);
return view;
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((androidx.viewpager.widget.ViewPager) arg0).removeView((View) arg2);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
@Override
public Parcelable saveState() {
return null;
}
//Note: For example
// main.xml add linear1
// custom middle.xml, farleft.xml, left.xml, right.xml
//middle.xml - linear1(textview1, textview2)
//farleft.xml - linear1(textview1, textview2, button1)
//left.xml - linear1(textview1, textview2)
//right.xml - liner1 and some with left.xml
Comments