我试图实现一个简单的应用程序,在主要活动中绘制一个黑色矩形,按下按钮。 例如,在MainActivity :
private Button button1; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); button1=(Button)findViewById(R.id.button); button1.setOnClickListener(new OnClickListener(){ public void onClick(View v) { switch(v.getId()){ case R.id.button: LinearLayout ll=(LinearLayout)findViewById(R.id.linearLayout1); System.out.println(ll.getWidth()+" "+ll.getHeight()); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ll.getWidth(),ll.getHeight()); YourView yourView = new YourView(getBaseContext()); yourView.setBackgroundColor(Color.WHITE); ll.addView(yourView,params); break; } } }); }
在YourView类中:
private Bitmap savedBitmap; public YourView(Context context) { super(context); } public void onDraw(Canvas canvas) { super.onDraw(canvas); System.out.println(canvas.getWidth()+" "+canvas.getHeight()); Paint textPaint = new Paint(); textPaint.setARGB(255, 0, 0, 0); textPaint.setTextAlign(Paint.Align.RIGHT); textPaint.setTextSize(11); textPaint.setTypeface(Typeface.DEFAULT); canvas.drawColor(Color.WHITE); System.out.println(canvas.getWidth()); System.out.println(canvas.getHeight()); canvas.drawRect(200, 20, 500, 100, textPaint); }
main.xml: