2011-12-15 60 views
0

* 我想在按下「bouton」按鈕之後在面板上畫一條名爲「maview」的線。但是我的程序在總體佈局上畫了一條線,並且按鈕消失了。 你有想法嗎?謝謝! * 我的代碼:在面板上繪圖

package esslineter.pack; 
import android.app.Activity; 
import android.os.Bundle; 
import android.graphics.Canvas; 
import android.graphics.Color; 
import android.graphics.Paint; 
import android.view.View; 
import android.widget.TextView; 
import android.content.Context; 

public class EsslineterActivity extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView (R.layout.main); 
    } 
    public void bouton (View view) 
    { 
     maView cv=new maView(this); 
     setContentView(cv); cv.invalidate(); 
    } 
    public class maView extends View 
    {    
      public maView(Context context) 
      { 
       super(context);     
      } 
      @Override 
      protected void onDraw(Canvas canvas) 
     { 
      Paint p = new Paint(); 
      p.setColor(Color.WHITE); 
      p.setStyle(Paint.Style.STROKE); 
      p.setStrokeWidth(3); 
      canvas.drawColor(Color.BLUE);      
      canvas.drawLine(0,0, 100, 100, p);           
     }     
    } 
} 

我的佈局:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 
    <TextView 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="@string/hello" /> 
    <Button 
     android:id="@+id/bouton1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:onClick="bouton" 
     android:text="draw line" /> 
    <View class="EsslineterActivity.maView" 
     android:id="@+id/surfaceView1" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_weight="0.86" /> 
</LinearLayout> 

回答

0

這是錯誤在你的onClick監聽器:

maView cv=new maView(this); 
setContentView(cv); 

您已經提供鑑於活動在onCreate - 這裏你說現在活動的基本視圖應該是maView。只需將這段代碼更改爲:

maView cv = (maView) findViewById(R.id.surfaceView1); 

在這裏,您不會創建新視圖,而是存在並在那裏繪製。

+0

謝謝你的回答,但正是你所說的,我得到一個「線程退出與未捕獲的異常(組= 0x40015560)」... ... – user1098281 2011-12-16 13:41:34

+0

你能提供完整的錯誤日誌嗎? – Jin35 2011-12-16 13:43:22

0

當您撥打setContentView(cv)時,您將更改整個活動佈局,因此一切消失,並且maView成爲屏幕上顯示的唯一視圖。

取而代之,您可以隱藏您的視圖到您的XML佈局(android:visibility="gone")中,並在單擊按鈕時顯示它。

<View class="EsslineterActivity.maView" 
    android:id="@+id/view1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:visibility="gone" /> 

並在代碼:

public void bouton (View view) 
{ 
    View maView = findViewById(R.id.view1); 
    maView.setVisibility(View.VISIBLE); 
} 

一般什麼是錯的,如果你要調用setContentView()多次在同一個活動。在onCreate()方法的開頭應該只調用一次。