Null pointer Exception - findViewById()

后端 未结 10 2727
情歌与酒
情歌与酒 2020-11-21 04:16

Can anyone help me to find out what can be the issue with this program. In the onCreate() method the findViewById() returns null for all ids and th

10条回答
  •  误落风尘
    2020-11-21 05:01

    add those views to the pager adapter before accessing them.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        adapter = new MyPagerAdapter();
        pager = (ViewPager) findViewById(R.id.main_pager);
        pager.setAdapter(adapter);
    
        layout1 = (LinearLayout) findViewById(R.id.first_View);
        layout2 = (LinearLayout) findViewById(R.id.second_View);
        layout3 = (LinearLayout) findViewById(R.id.third_View);
    
    }
    

    in the pager adapter:

    public Object instantiateItem(View collection, int position) {
        if(position == 0){
            View layout = inflater.inflate(R.layout.activity_first, null);
    
            ((ViewPager) collection).addView(layout);
    
            return layout;
        } 
        ... and so forth.
    
    }
    

    from here you can access them via findViewById.

提交回复
热议问题