Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

listener - Android: The method OnClickListener() is undefined for the type View

I'm getting an error: The method OnClickListener() is undefined for the type View

I'm new to android dev. These are my code:

package com.example.playword;

import java.io.IOException;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

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

        //final Handler mHandler = new Handler();

        final TextView nicholas = (TextView) findViewById(R.id.nicholas);
        final TextView was = (TextView) findViewById(R.id.was);

        nicholas.setText("Nicholas ");
        was.setText("was ");

        View.OnClickListener handler = View.OnClickListener(){
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.nicholas: // doStuff
                        nicholas.setText("Nicholas (Clicked!) ");
                        break;
                    case R.id.was: // doStuff
                        was.setText("was (Clicked!) ");
                        break;
                }
            }
        }

        findViewById(R.id.nicholasBtn).setOnClickListener(handler);
        findViewById(R.id.wasBtn).setOnClickListener(handler);

    }
}

The error highlights in these lines:

        View.OnClickListener handler = View.OnClickListener(){
            public void onClick(View v) {

Many thanks in advance! :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You forgot the new keyword, and a semicolon:

View.OnClickListener handler = new View.OnClickListener(){
    ...
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...