button.setOnClickListener给了我错误

时间:2011-10-25 21:14:33

标签: android

 Button myButton = new Button(this);
        myButton.setText("Change View");
        myButton.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        myButton.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                Context context = getApplicationContext();
                CharSequence text = "Hello toast!";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();

                }
        });

这段代码究竟出了什么问题?它给我一个错误,我设置onClickListener。我还必须删除@override以上的公共空白,尽管其他例子都有它们。

2 个答案:

答案 0 :(得分:2)

由于Button是一个视图,您应该创建View.OnClickListener

myButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Context context = getApplicationContext();
        CharSequence text = "Hello toast!";
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
     }
});

答案 1 :(得分:1)

在我看来,在main.xml上声明按钮更容易

<Button
        android:id="@+id/mybutton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Change View"
        android:onClick="onClick">
</Button>

并声明方法onClick on Activity class

public void onClick(View v) {
   Context context = getApplicationContext();
   CharSequence text = "Hello toast!";
   int duration = Toast.LENGTH_SHORT;

   Toast toast = Toast.makeText(context, text, duration);
   toast.show();
}