2011-11-16 70 views
1

我有一個簡單的程序在Android上繪製用戶觸摸。使用MySurfaceView和main.xml(安卓)

這裏的主要活動:

public class DrawingActivity extends Activity { 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    //setContentView(new MySurfaceView(this)); - this way it works, but 
              // i'm interseted in previous 
} 
} 

這是main.xml中:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 

<com.shchurov.MySurfaceView 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:id="@+id/msv" 
/> 
</LinearLayout> 

和這裏的MySurfaceView類:

public class MySurfaceView extends SurfaceView 
      implements SurfaceHolder.Callback { 

private SurfaceHolder surfaceHolder; 
Canvas canvas=null; 
Paint paint=new Paint(); 


public MySurfaceView(Context context) { 
    super(context); 
    getHolder().addCallback(this); 
    paint.setColor(Color.GREEN); 
    paint.setStyle(Style.FILL); 
} 

@Override 
public void surfaceChanged(SurfaceHolder holder, int format, int width, 
     int height) { 
} 

@Override 
public void surfaceCreated(SurfaceHolder holder) { 
    this.surfaceHolder=holder; 
} 

@Override 
public void surfaceDestroyed(SurfaceHolder holder) { 
} 

public boolean onTouchEvent(MotionEvent event) 
{ 
    canvas=surfaceHolder.lockCanvas(null); 
    canvas.drawCircle(event.getX(), event.getY(), 10, paint); 
    surfaceHolder.unlockCanvasAndPost(canvas); 
    return true; 
} 

} 

包是正確的,但由於某種原因它不沒有工作,任何人都可以幫忙嗎?

更新:如果我改變MySurfaceView以此爲榜樣,那麼它的工作原理:

public class MySurfaceView extends View 
{ 
Paint paint; 
public SomeView(Context context, AttributeSet attrs) 
{ 
    super(context, attrs); 
    paint = new Paint(); 
    paint.setColor(Color.YELLOW); 
    paint.setStyle(Style.FILL); 
} 

@Override 
protected void onDraw(Canvas canvas) 
{ 
    canvas.drawCircle(20, 20, 20, paint); 
} 
} 
+0

嘗試使用fill_parent作爲表面視圖的高度和寬度。 –

+0

感謝您的幫助,但它無法正常工作。有趣的時刻:如果我改變MySurfaceView的東西比它更簡單的工作 – user1049280

回答

1

layout_width = 「FILL_PARENT」

layout_height = 「FILL_PARENT」

的surfaceview標籤內,將解決你的問題。

+0

非常感謝您的幫助,但正如我寫上,它不工作。我也更新了問題 – user1049280

+0

嘗試在更大的SurfaceView中將構造函數更改爲MySurfaceView(上下文上下文,AttributeSet attrs)。 – c05mic

+0

現在工作,謝謝你的幫助:) – user1049280

0

你需要/要實現所有三個構造一個視圖可以有:

//Simple constructor to use when creating a view from code. 
View(Context context) 

//Constructor that is called when inflating a view from XML. 
View(Context context, AttributeSet attrs) 

//Perform inflation from XML and apply a class-specific base style. 
View(Context context, AttributeSet attrs, int defStyle) 

這是剛剛從View class constructor details in the documentation複製。