OnClickListener无法解析为某种类型

问题描述 投票:5回答:3

我正在深入研究Java(这是第1天),我正在尝试创建一个按钮,当我点击它时会触发通知...

此代码基于通知文档here和UI事件文档here

package com.example.contactwidget;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;

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

        Button calc1 = (Button) findViewById(R.id.calc_button_1);
        calc1.setOnClickListener(buttonListener);

        setContentView(R.layout.main);
    }

    private static final int HELLO_ID = 1;

    //Error: OnClickListener cannot be resolved to a type
    private OnClickListener buttonListener = new OnClickListener() {
        public void onClick (View v) {
            String ns = Context.NOTIFICATION_SERVICE;
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

            int icon = R.drawable.icon;
            CharSequence ticketBrief = "Button Pressed Brief";
            CharSequence ticketTitle = "Button pressed";
            CharSequence ticketText = "You pressed button 1";
            long when = System.currentTimeMillis();

            Notification notification = new Notification(icon, ticketBrief, when);

            Intent notificationIntent = new Intent(this, ContactWidget.class);
            PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

            notification.setLatestEventInfo(getApplicationContext(), ticketTitle, ticketText, contentIntent);

            mNotificationManager.notify(HELLO_ID, notification);
        }
    }
}

我遇到了一个问题:OnClickListener cannot be resolved to a type。这里的问题是我没有看到我的代码与我正在使用的示例有任何问题

java android
3个回答
22
投票

添加此导入:

import android.view.View.OnClickListener;

如果您使用的是Eclipse,则可以使用Ctrl + Shift + O使其自动导入这些clases或接口。


2
投票

确保您同时拥有这两种导入:

import android.view.View;
import android.view.View.OnClickListener;

0
投票
setContentView(R.layout.main);

应该在按钮声明之上,就在下面

super.onCreate(savedInstanceState);