2011-09-14 35 views
1

我有一個現有的xml佈局,我在我的活動類中加載此佈局。現在我想在底部繪製一個矩形。點擊時會調用新的意圖。如何將這個矩形添加到我現有的佈局中。android如何在現有的佈局中繪製圖形

public void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.chart); 

這是繪製圖形的代碼..我該如何做到這一點?

drawView = new DrawView(this); 
     drawView.setBackgroundColor(Color.WHITE); 
     setContentView(drawView); 

回答

2

活動與繪製UI無關(在任何情況下,他們都不會直接這樣做)。視圖類負責繪圖。

在你的情況下,你可能應該擴展你的自定義類的Button類。重寫onMeasure()使其成爲正方形。背景將是你設定的任何東西。


一個簡單的例子:

SquareButton.java

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:a="http://schemas.android.com/apk/res/android" 
    a:orientation="vertical" 
    a:layout_width="fill_parent" 
    a:layout_height="fill_parent" 
    a:gravity="center" 
    a:weightSum="1"> 

    <com.inazaruk.helloworld.SquareButton 
     a:id="@+id/button" 
     a:layout_height="0dp" 
     a:layout_weight="0.5"   
     a:layout_width="fill_parent"   
     a:background="#ffffffff" 
     a:text="foo" 
     a:gravity="center" 
     /> 

</LinearLayout> 

結果的屏幕截圖:使用該按鈕main.xml

package com.inazaruk.helloworld; 

import android.content.Context; 
import android.util.AttributeSet; 
import android.widget.Button; 

public class SquareButton extends Button 
{ 
    public SquareButton(Context ctx) 
    { 
     super(ctx); 
    } 

    public SquareButton(Context ctx, AttributeSet attrs) 
    { 
     super(ctx, attrs); 
    } 

    public SquareButton(Context ctx, AttributeSet attrs, int defStyle) 
    { 
     super(ctx, attrs); 
    } 

    @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) 
    { 
     super.onMeasure(widthMeasureSpec, heightMeasureSpec);   

     /* currently view is rectangle, so we get the shorter size 
     * and make it square. */ 

     int width = getMeasuredWidth(); 
     int height = getMeasuredHeight(); 

     width = height =(int) (Math.min(width, height));   

     super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), 
         MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); 
    } 
} 

佈局
enter image description here