Good day.

Trying to bring ViewPager into layout. I am writing this code

ViewPager viewPager = (ViewPager) findViewById(; viewPager.setAdapter(pagerAdapter); viewPager.setCurrentItem(1); setContentView(R.layout.activity_main); 

Activity_main.xml file

 <LinearLayout xmlns:android="" xmlns:tools="" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" > < android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> 

The application fails. And when I form a layer it works dynamically.

 LinearLayout linLayout = new LinearLayout(this); linLayout.setOrientation(LinearLayout.HORIZONTAL); ViewPager viewPager = new ViewPager(this); viewPager.setAdapter(pagerAdapter); viewPager.setCurrentItem(1); linLayout.addView(viewPager); 

    1 answer 1

    In the first variant, put the line setContentView (R.layout.activity_main); the very first and everything will work. You can’t search for a view where you haven’t even set it as content

    • Thank you very much. Everything worked out. - hardcor4uk