Dynamic ViewPager:-
in Activity :
public class MainActivity extends AppCompatActivity {
ViewPager mPager;
int numPages = 0;
String[] mImageArray;
int addNext = 0;
EndLessAdapter adapter;
ArrayList<String> arrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrayList = new ArrayList<>();
String number = getIntent().getStringExtra("number");
numPages = Integer.parseInt(number);
mImageArray = new String[numPages];
addNext = numPages;
for (int i = 0; i < numPages; i++) {
mImageArray[i] = "Click " + String.valueOf(i + 1);
arrayList.add("Click " + String.valueOf(i + 1));
}
mPager = (ViewPager) findViewById(R.id.frame);
mPager.setOffscreenPageLimit(0);
adapter = new EndLessAdapter(this, arrayList);
mPager.setAdapter(adapter);
}
public void addNewpage() {
arrayList.add("Click " + String.valueOf(addNext + 1));
adapter.notifyDataSetChanged();
addNext = addNext + 1;
}
public class EndLessAdapter extends PagerAdapter {
FragmentActivity activity;
ArrayList<String> stringArrayList1;
// String imageArray[];
private int pos = 0;
public EndLessAdapter(FragmentActivity act, ArrayList<String> stringArrayList) {
stringArrayList1 = stringArrayList;
activity = act;
}
public int getCount() {
return Integer.MAX_VALUE;
//return imageArray.length;
}
public Object instantiateItem(View collection, int position) {
Button mwebView = new Button(activity);
((ViewPager) collection).addView(mwebView, 0);
// mwebView.setScaleType(ImageView.ScaleType.FIT_XY);
mwebView.setText(stringArrayList1.get(pos));
mwebView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addNewpage();
}
});
if (pos >= stringArrayList1.size() - 1)
pos = 0;
else
++pos;
return mwebView;
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
@Override
public Parcelable saveState() {
return null;
}
}
}
in XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.com.dynamicviewpager_android.MainActivity">
<android.support.v4.view.ViewPager
android:id="@+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true" >
</android.support.v4.view.ViewPager>
</RelativeLayout>
No comments:
Post a Comment