将单击侦听器设置为按钮时出错

时间:2014-12-22 01:03:10

标签: java android onclicklistener

我试图为我的activity_main布局中声明的按钮添加onClick()但是当我尝试在MainActivity.java中声明一个按钮时,我收到错误:

The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (MainActivity)

我已经搜索了错误并找到了解决方案,说明要导入以下import android.view.View.OnClickListener;,但这并没有解决问题。

有人能发现我的实施有什么问题吗?

以下是声明按钮和随附的case语句的代码:

protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button mClickButton1 = (Button)findViewById(R.id.cameraBtn);
        mClickButton1.setOnClickListener(this);
        Button mClickButton2 = (Button)findViewById(R.id.searchBtn);
        mClickButton2.setOnClickListener(this);



    }


//handle button clicks
    public void onClick(View v) {
        switch (v.getId()) {
            case  R.id.cameraBtn: {
                // start camera intent
                 Toast.makeText(this, "camera clicked", Toast.LENGTH_SHORT).show();
                break;
            }

            case R.id.searchBtn: {
                // search tree for matching debri
                 Toast.makeText(this, "search clicked", Toast.LENGTH_SHORT).show();
                break;
            }
        }
    }

1 个答案:

答案 0 :(得分:2)

您需要声明您正在实施界面......

public class MyActivity extends Activity implements View.OnClickListener {