Null pointer Exception - findViewById()

后端 未结 10 2683
情歌与酒
情歌与酒 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 04:59

    Emphasis added

    For those cases within an Activity class.

    Activity.findViewById(int id)

    Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle).


    Otherwise, such as an Fragment, Adapter, a View from a LayoutInflater, etc.

    View.findViewById(int id)

    Look for a child view with the given id. If this view has the given id, return this view.


    Either case,

    Returns
    The view if found or null otherwise.


    Now, re-check your XML files. Make sure you put the right value into setContentView or inflater.inflate.

    In the case of an Activity, call findViewById after setContentView.

    Then, make sure there is a View you are looking for with android:id="@+id/..." in that layout. Make sure the + is at @+id, which will add the resource to the R.id values to ensure you can find it from Java.

提交回复
热议问题