2012-06-20 102 views
2

我試圖刷新屏幕上點擊一個按鈕,所以我想知道我應該寫在OnClick()方法,以便自定義視圖,即TouchEventView將重新加載或刷新在這裏是我的 TouchEventView.java點擊一個按鈕重新加載自定義視圖

public class TouchEventView extends View { 
    private Paint paint = new Paint(); 
    private Path path = new Path(); 

    public TouchEventView(Context context, AttributeSet attrs) { 
     super(context, attrs); 

     paint.setAntiAlias(true); 
     paint.setColor(Color.WHITE); 
     paint.setStyle(Paint.Style.STROKE); 
     paint.setStrokeJoin(Paint.Join.ROUND); 
     paint.setStrokeWidth(5f); 
    } 

    @Override 
    protected void onDraw(Canvas canvas) { 
     canvas.drawPath(path, paint); 
    } 

    @Override 
    public boolean onTouchEvent(MotionEvent event) { 
     float eventX = event.getX(); 
     float eventY = event.getY(); 

     switch (event.getAction()) { 
     case MotionEvent.ACTION_DOWN: 
      path.moveTo(eventX, eventY); 

      return true; 
     case MotionEvent.ACTION_MOVE: 
      path.lineTo(eventX, eventY); 
      break; 
     case MotionEvent.ACTION_UP: 
      // nothing to do 
      break; 
     default: 
      return false; 
     } 

     // Schedules a repaint. 
     invalidate(); 
     return true; 
    } 
} 
` 

這裏的代碼是main.xml中的文件``

<de.vogella.android.touch.TouchEventView 
     android:id="@+id/mydrawview1" 
     android:layout_width="wrap_content" 
     android:layout_height="328dp" 
     android:layout_weight="0.91" /> 

    <LinearLayout 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" > 

     <Button 
      android:id="@+id/reset" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Reset" /> 
    </LinearLayout> 

</LinearLayout>` 

這裏是活動class`

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    Button res = (Button) findViewById(R.id.reset); 
    res.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      TouchEventView touchView = (TouchEventView) findViewById(R.id.mydrawview1); 
      touchView.clear(); 

     } 
    }); 
} 

}`

+0

沒有足夠的信息。 – JoxTraex

+0

我想重新加載自定義視圖(TouchEventView)點擊按鈕重置。 –

回答

5

這種方法只需添加到您的TouchEventView

public void clear() 
{ 
    path = new Path(); 
    invalidate(); 
} 

然後從onClick()調用它:

@Override 
public void onClick(View v) { 
    TouchEventView touchView = (TouchEventView) findViewById(R.id.mydrawview1); 
    touchView.clear(); 
} 
+0

非常感謝...它的工作:) –

+0

我不能直接像? @Override public void onClick(View v){ TouchEventView touchView =(TouchEventView)findViewById(R.id.mydrawview1); touchView.invalidate(); } –

+0

@swatisinha否,因爲您需要創建一個新的路徑以及視圖無效。我會推薦做我的解決方案。 – monchote

相關問題