How to add custom view to the layout?

后端 未结 7 1714
灰色年华
灰色年华 2020-11-30 07:35

I have a GraphicsView class that extends from the View class and I want to add this GraphicsView class to the main layout in my projec

7条回答
  •  爱一瞬间的悲伤
    2020-11-30 08:15

    public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
    
        LinearLayout v = (LinearLayout) findViewById(R.id.linearLayout);
        MyGraphics myView = new MyGraphics(this);
        v.addView(myView);
    }
    }
    
    
    public class MyGraphics extends View {
    public MyGraphics(Context context) {
        super(context);
    }
    
    @Override
    protected void onDraw(Canvas canvas) {
        // Drawing commands go here
        Path rect = new Path();
        rect.addRect(100, 100, 250, 50, Direction.CW);
        Paint cPaint = new Paint();
        cPaint.setColor(Color.LTGRAY);
        canvas.drawPath(rect, cPaint);
    }
    
    
    }
    

    XML:

    
    

    
    
    
    
    

提交回复
热议问题