2011-12-15 59 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()方法的开头应该只调用一次。