View Inflation and custom views

前端 未结 2 745
长发绾君心
长发绾君心 2021-01-13 17:45

I have a custom view in my app that I draw using the onDraw() function in the View. Also it needs some data from the ACtivity to draw the graphic. So instead of

2条回答
  •  花落未央
    2021-01-13 18:28

    onFinishInflate ()

    Finalize inflating a view from XML. This is called as the last phase of inflation, after all child views have been added.

    When you create your view by code (new ...) you are not inflating it... on the other hand, if you declare it in the XML or you use something like getLayoutInflater().inflate(R.layout.your_view,null,null); then you are inflating it (and onFinishInflate) will be called.

    It does not matter how you are doing it, onDraw method will always be called; so you don't have to invoke it manually.

    By the way... it's always a good idea to keep your custom view on the XML, even if it needs data. So you have at least two options:

    setContentView(R.layout.your_layout);
    YourCustom custom = (YourCustom)findViewById(R.id.custom);
    custom.setUserData(userData);
    

    or... you can fetch that data from the custom view (not recommended):

    // inside your custom view...
    UserData userData = Someclass.getUserData(getContext());
    // etc... so that you don't have to pass it from the activity
    

提交回复
热议问题