nebyan
nebyan

Reputation: 9407

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.

Upvotes: 4

Views: 7521

Answers (2)

Piotr Gorajski
Piotr Gorajski

Reputation: 396

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).

Upvotes: 11

Yahor10
Yahor10

Reputation: 2132

Create viewPager with FragmentActivity and

 new MyPagerAdapter(
                getSupportFragmentManager());

Upvotes: 0

Related Questions