这将是一个真正的新手问题,请多多包涵。我正在尝试在Android中创建一个消息框来响应按钮点击事件。我已经阅读了一些StackOverflow上的示例,但似乎无法掌握概念。在我的main.xml文件中,我已定义了以下按钮xml:
<Button
android:id="@+id/btnOK"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display Message"
android:onClick="onBtnClicked" />
我在一个帖子上读到需要在XML布局中注册onClick事件,所以我认为我已经在上面的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代码中的定义会自动创建它,但似乎不是这样?
提前感谢 :-)