Android create ViewPager programmatically

ぐ巨炮叔叔 提交于 2019-12-21 05:16:05

问题


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.


回答1:


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




回答2:


Create viewPager with FragmentActivity and

 new MyPagerAdapter(
                getSupportFragmentManager());


来源:https://stackoverflow.com/questions/12173792/android-create-viewpager-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!