1

我有一个有按钮的活动,我想在按下按钮来敬酒时,我这样做了:

public class myActivity extends Activity implements OnClickListener {

    EditText nameEditText;
    Button okButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        nameEditText = (EditText) findViewById(R.id.editText);
        okButton = (Button) findViewById(R.id.button);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.button:
            Toast.makeText(myActivity.this, "Pressed", Toast.LENGTH_LONG)
                    .show();
            break;

        default:
            break;
        }
    }
}

哪里错了?

谢谢你

4

3 回答 3

4

你忘记为你的按钮设置监听器

因为您的活动已经在实现接口,所以您onClickListener必须okButton.setOnClickListener(this);在函数中添加。请检查以下代码:okButton = (Button) findViewById(R.id.button);onCreate

我的活动.java

public class myActivity extends Activity implements OnClickListener {

        EditText nameEditText;
        Button okButton;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            nameEditText = (EditText) findViewById(R.id.editText);
            okButton = (Button) findViewById(R.id.button);
                okButton.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
            case R.id.button:
                Toast.makeText(myActivity.this, "Pressed", Toast.LENGTH_LONG)
                        .show();
                break;

            default:
                break;
            }
        }
    }
于 2013-04-06T08:46:36.197 回答
2

在您的 onCreate 方法上,您必须添加一个寄存器

okButton.setOnClickListener(this);  

okButton = (Button) findViewById(R.id.button);
于 2013-04-06T08:48:37.637 回答
0

您丢失了okButton = setOnClickListenre(this),因为您的活动在点击侦听器上实现。后插入此代码okButton = (Button) findViewById(R.id.button);

于 2013-04-06T08:55:55.723 回答