-1

我是android编程的新手。我看到了很多方法来进行事件处理,但是当我尝试通过调用处理程序类来完成它时,它会在处理类名时出错:

package com.example.test;

import android.app.Activity;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //attach an instance of HandleClick to the Button
        findViewById(R.id.button1).setOnClickListener(new HandleClick());
    }    

    private class HandleClick implements OnClickListener{
        public void onClick(View arg0) {
            Button btn = (Button)arg0;  //cast view to a button
            // get a reference to the TextView
            TextView tv = (TextView) findViewById(R.id.textview1);
            // update the TextView text
            tv.setText("You pressed " + btn.getText());
        }
    }
}

"HandleClick"错误来了,它说类应该是抽象类型?

我不明白为什么会出现此错误,任何人都可以帮助我吗?

4

3 回答 3

2

那是错误的 OnClickListener 类。你有

 import android.content.DialogInterface.OnClickListener;

你需要:

 import android.view.View.OnClickListener;

为了将来参考,您得到的错误是“类型必须实现继承的抽象方法......”。这是因为您需要实现 DialogInterface 的 onClick,这应该会导致您注意到它是错误的导入(因为您有onClick(View)

于 2013-01-09T17:06:39.270 回答
0

让它变得简单并使用它,

b1 = (Button) findViewById(R.id.button1);
TextView tv = (TextView) findViewById(R.id.textview1);
b1.setOnClickListener(new OnClickListener()
{
    public void onClick(View v)
    {
        Toast msg = Toast.makeText(getBaseContext(),
        "You have clicked Button 1", Toast.LENGTH_LONG);
        msg.show();
        tv.setText("You pressed " + btn.getText());
    }
});
于 2013-01-09T17:07:07.563 回答
0

你导入了错误的 OnClickListener,你应该从 android.view.View 导入那个

于 2013-01-09T17:08:54.493 回答