2013-06-13 16 views
0

我試圖設置一個按鈕,點擊後,在我創建的視圖的子類中調用一個函數。但即使我完全按照幫助頁上所寫的方式來跟蹤Android文檔,但我仍然收到錯誤消息。實際上使用onClickListener聲明點擊事件時出錯

這是我的主要活動:

public class MainActivity extends Activity{ 

@Override 
protected void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

這裏是包含我試圖訪問該函數的類,用一段代碼,試圖在佈局,以配合一鍵功能沿我試圖運行(它清除列表):

public class Drawing extends View implements OnTouchListener{ 

private ArrayList<Line> lines = new ArrayList<Line>(); 

Button resetButton = (Button)findViewById(R.id.button2); 
resetButton.setOnClickListener(new View.OnClickListener(){ 
    public void onClick(View v){ 
     eraseLines(); 
    } 
}); 


public Drawing(Context context, AttributeSet xmlAttributes){ 
    super(context, xmlAttributes); 
    setOnTouchListener(this); 
} 


public void eraseLines(){ 
    lines.clear(); 
} 

什麼我做錯了,讓我從能夠簡單地已經按鈕運行eraseLines()函數的類圖紙?

任何幫助非常感謝!

+0

你可以張貼logcat的? – Neoh

+0

應用程序進入onCLick()函數嗎?可能是錯誤的:你實現了Ontouchlistener而不是onclick監聽器? – Vyacheslav

+0

你真的在你的** Drawing **類中實現了OnTouchListener嗎?您是否重寫了_onTouch(View v,MotionEvent event)_?方法? –

回答

0

我的猜測是,當你檢索你的按鈕時,你的視圖的佈局不適當膨脹,因此它的引用可能爲空。

你應該這樣做:

public class Drawing extends View implements OnTouchListener{{ 

    private ArrayList<Line> lines = new ArrayList<Line>(); 

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

    // Inflate layout prior to retrieving the button 
    LayoutInflater.from(context).inflate(R.layout.your_drawing_layout, this, true); 

    // Assuming 'button2' id exists in 'your_drawing_layout' 
    Button resetButton = (Button)findViewById(R.id.button2); 
    resetButton.setOnClickListener(new View.OnClickListener(){ 
     public void onClick(View v){ 
      eraseLines(); 
     } 
    }); 

    } 

    public void eraseLines(){ 
    lines.clear(); 
    } 

    @Override 
    public boolean onTouch(View v, MotionEvent event){ 
    // Implementation of onTouch 
    } 
}