Null pointer Exception - findViewById()

后端 未结 10 2723
情歌与酒
情歌与酒 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.

    0 讨论(0)
  • 2020-11-21 05:04

    The findViewById method must find what is in the layout (which you called in the setContentView)

    0 讨论(0)
  • 2020-11-21 05:10

    The views you're trying to get are not defined in your activity_main layout. You need to programmatically inflate the views you're trying to add to the pager.-

    @Override
    public Object instantiateItem(ViewGroup collection, int position) {
        LinearLayout l = null;
    
        if (position == 0) {
            l = (LinearLayout) View.inflate(this, R.layout.activity_first, null);
        }
        if (position == 1) {
            l = (LinearLayout) View.inflate(this, R.layout.activity_second, null);
        }
        if (position == 2) {
            l = (LinearLayout) View.inflate(this, R.layout.activity_third, null);
        }
    
        collection.addView(l, position);
        return l;
    }
    
    0 讨论(0)
  • 2020-11-21 05:12

    In Android, findViewById(R.id.some_id) works when you are finding view in the layout set.

    That is, if you have set a layout say:

    setContentView(R.layout.my_layout);
    

    Views can be found only in this layout (my_layout).

    In your code layout1, layout2, layout3 all are three different layouts and they are not set to the activity.

    0 讨论(0)
提交回复
热议问题