2015-06-20 57 views
3

現在我正在研究將在onClick上畫線的應用程序。我正在LineView.java班上畫線,並在MainActivity.java上表演onClick方法。爲了解決這個問題,我檢查了類似的問題。 第一個解決方案:Android如何從另一個類別調用方法

LineView.onDraw(); 

它給我這個錯誤:

Multiple markers at this line 
    - The method onDraw(Canvas) in the type LineView is not applicable for the 
    arguments() 
    - Suspicious method call; should probably call "draw" rather than "onDraw" 

我也試過在MainActivity寫:

LineView lineView = new LineView(null); 
lineView.onDraw(); 

但它也提供了一個錯誤:

Multiple markers at this line 
    - The method onDraw(Canvas) in the type LineView is not applicable for the 
    arguments() 
    - Suspicious method call; should probably call "draw" rather than "onDraw" 

她E公司我LineView.java:

public class LineView extends View { 
Paint paint = new Paint(); 
Point A; 
Point B; 
boolean draw = false; 

public void onCreate(Bundle savedInstanceState) { 

} 

public LineView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    } 

public LineView(Context context, AttributeSet attrs, int defstyle) { 
super(context, attrs, defstyle); 
    } 


public LineView(Context context) { 
super(context); 
paint.setColor(Color.BLACK); 
} 

@Override 
public void onDraw(Canvas canvas) { 
    draw = MainActivity.draw; 
    if(draw){ 
    //A = (getIntent().getParcelableExtra("PointA")); 
    A = MainActivity.A; 
    B = MainActivity.B; 

    canvas.drawLine(A.x, A.y, B.x, B.y, paint); 
    } 
} 

private Intent getIntent() { 
    // TODO Auto-generated method stub 
    return null; 
} 

} 

MainActivity.javaonClick

@Override 
     public void onClick(View v) { 
      draw = true; 
         LineView.onDraw(); 
        } 
    }); 

提前感謝!

+0

你有沒有將LineView添加到任何佈局或動態初始化LineView? –

+0

是的。我在我的layout_main中有LineView –

回答

0

你不應該直接在任何View上調用onDraw()。 視圖繪製自己,如果它們是可見的,並在視圖層次結構。 如果您需要的視圖中繪製本身,因爲事情已經改變(如您的A和B變量),那麼你應該做這樣的事情:

LineView.invalidate(); 

無效()告訴該觀點已經改變了UI系統和應該在不久的將來調用onDraw()(可能是UI線程的下一次迭代)。

我認爲你的'繪製'變量可能是不必要的。如果您想要隱藏視圖,請使用setVisibility()。

+0

這不起作用。它說它不能從View類型中對非靜態方法invalidate()進行靜態引用。我不能以某種方式在MainActivity中使用onDraw()嗎? –

+0

您需要對LineView類的實例調用invalidate,而不是類本身。如果你沒有對你的LineView對象的引用,那麼你可以通過這種方式從你的佈局中獲得它''(LineView)mainView.findViewById(R.id.id_of_LineView);' –

+0

另請參閱這裏:[鏈接](http: //stackoverflow.com/questions/3903537/i-want-to-know-the-difference-between-static-method-and-non-static-method) –

相關問題