findViewById() returns null for custom component in layout XML, not for other components

前端 未结 18 1497
情歌与酒
情歌与酒 2020-11-28 10:36

I have a res/layout/main.xml including these elements and others:



        
18条回答
  •  北海茫月
    2020-11-28 11:34

    This happened to me with a custom component for Wear, but is a generic piece of advice. If you're using a Stub (such as I was using WatchViewStub), you can't just put the call to findViewById() anywhere. Everything inside the stub must be inflated first, which doesn't just happen after setContentView(). Thus, you should write something like this in order to wait for that to happen:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wear);
        final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
        stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
            @Override
            public void onLayoutInflated(WatchViewStub stub) {
                myCustomViewInst = (MyCustomView) findViewById(R.id.my_custom_view);
                ...
    

提交回复
热议问题