Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android create ViewPager programmatically

I create a view pager programmatically and I add this view pager into layout but it doesn't run.

ViewPager viewPager = new ViewPager(this);
viewPager.setAdapter(new MyPagerAdapter());
addView(viewPager);

The view pager is not working; but when I use it from XML it works fine. I want to use it dynamically.

like image 1000
nebyan Avatar asked Dec 20 '22 16:12

nebyan


1 Answers

Please, post also the code of 'addView' method. Right now I would only suggest adding some layout attributes like width and height to your viewPager.

UPDATE: Ok, I just encountered that problem in my project. The only attribute that you have to set for viewPager to make it work is id. How to obtain unique id (which is generated in R class) without having a component defined in the xml file is written here: Android: View.setID(int id) programmatically - how to avoid ID conflicts? (the post with ids.xml in res/values answer).

like image 83
Piotr Gorajski Avatar answered Jan 01 '23 16:01

Piotr Gorajski