2012-01-08 128 views
6

這將是一個真正的noob問題,所以請有憐憫。我正在嘗試在Android中的按鈕單擊事件上創建一個消息框。我已經閱讀了一些關於StackOverflow的例子,但我似乎無法理解這個概念。Android上的按鈕點擊事件

<Button 
android:id="@+id/btnOK" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:text="Display Message" 
android:onClick="onBtnClicked" /> 

我上,我需要註冊在XML佈局onClick事件的職位之一閱讀:在我的main.xml文件,內容如下我定義按鈕XML。這就是我以爲我在上面的XML代碼中所做的。然後,在我的java代碼文件中,我寫了下面的代碼:

package com.example.helloandroid; 

import android.app.Activity; 
import android.content.DialogInterface; 
import android.content.DialogInterface.OnClickListener; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.Toast; 

public class HelloAndroid extends Activity 
{ 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main);   
    } 

    public void onBtnClicked(View v) 
    { 
     if(v.getId() == R.id.btnOK) 
     { 
      MessageBox("Hello World"); 
     }  
    } 

    public void MessageBox(String message) 
    { 
     Toast.makeText(this, message, Toast.LENGTH_SHORT); 
    } 
} 

對我來說,這是有道理的。但是當我點擊按鈕時,消息框不顯示。從上面的代碼導入,你可以看到我已經嘗試了幾個解決方案,但沒有成功。我可能錯過了一個聽衆?我認爲XML代碼中的定義會爲我創建這個?

在此先感謝:-)

回答

6

變化

Toast.makeText(this, message, Toast.LENGTH_SHORT); 

Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); 

展示()可確保您實際顯示吐司,否則你只是在創建吐司。

+0

非常感謝!這工作! – 2012-01-08 21:31:55

1

Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); - 您需要調用show()方法,因爲您現在只是在不顯示它的情況下創建敬酒。

+0

非常感謝! – 2012-01-08 21:34:23

0

活動必須實現View.OnClickListener,且實施方法的onClick(視圖v)

在onCreate方法

,你必須初始化按鈕(該指令的setContentView後):

Button b = (Button) findViewById(R.id.btnOK); 
b.setOnClickListener(this); 

在方法的onClick:

public void onClick(View v) { 
    switch(v.getId()){ 
    case R.id.btnOK: 
     /* the instruccions of the button */ 
     break; 
    } 
} 
+0

感謝您的反饋! – 2012-01-08 21:40:19

1
Toast.makeText(this, message, Toast.LENGTH_SHORT); 

這是正確的

Toast.makeText(this, message, Toast.LENGTH_SHORT).show();