View Inflation and custom views

前端 未结 2 766
长发绾君心
长发绾君心 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:42

    What you should have here is a layout that contains the TextView and your MyView and then inside your activity, find your custom view and pass in your user data. Your MyView can then use this during its onDraw(). Perhaps something like this:

    res/layout/main.xml:

    
        
        
    
    

    src/my/package/MyView.java:

    public class MyView extends View {
        UserData mUserData = null;
        public void setUserData(userData) {
            mUserData = userData;
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            performCustomDrawingWithUserData(mUserData);
            super.onDraw(canvas);
        }
    
    }
    

    src/my/package/MyActivity.java:

    public class MyActivity extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            // pass the user data into myview here.
            MyView myView = (MyView) findViewById(R.id.myview);
            myView.setUserData(userData);
        }
    
    }
    

提交回复
热议问题