[英]Issues overriding onKey in View.OnKeyListener
I am new to Android programming and relatively new to programming in general so please bear with me here... 我是Android编程的新手,而对于编程又是一个相对较新的人,所以请在这里忍受...
I am trying to implement an EditText field and I am having problems with overriding onKey. 我正在尝试实现EditText字段,并且在覆盖onKey时遇到问题。
I found a couple of errors and fixed them but when I compile I get the following error: 我发现了几个错误并进行了修复,但是在编译时出现以下错误:
cs211d.hw03.HW03 is not abstract and does not override abstract method onKey(android.view.View,int,android.view.KeyEvent) in android.view.View.OnKeyListener
[javac] public class HW03 extends Activity implements View.OnKeyListener
I tried moving the onKey
method outside of the inner class and it worked but only if I commented out et.setOnKeyListener(...);
我尝试将
onKey
方法移到内部类之外,但它只在我注释掉et.setOnKeyListener(...);
Somebody suggested in another forum that I remove the OnKeyListener
and/or implements View.OnKeyListener
but it seems like it should be possible to implement the interface and use the OnKeyListener
....otherwise what is the point of it's existence? 有人在另一个论坛上建议我删除
OnKeyListener
和/或implements View.OnKeyListener
但似乎应该可以实现该接口并使用OnKeyListener
...。否则,它的意义是什么?
Here is my code: 这是我的代码:
import android.app.Activity;
import android.os.Bundle;
import android.view.*;
import android.widget.EditText;
public class HW03 extends Activity implements View.OnKeyListener
{
final EditText et = (EditText) findViewById(R.id.penniesField);
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle b)
{
super.onCreate(b);
setContentView(R.layout.main);
et.setOnKeyListener(
new View.OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent ke)
{
if( (ke.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER) )
{
String pennies = et.getText().toString();
return true;
}
return true;
}
});
}
}
I'm not sure what the problem is exactly. 我不确定到底是什么问题。 I ran this piece of code and if I typed "hello" in the EditText and pressed Enter, "pennies" would contain the word "hello".
我运行了这段代码,如果我在EditText中键入“ hello”并按Enter,则“ pennies”将包含单词“ hello”。
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
ll.addView(et);
et.setOnKeyListener(
new View.OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent ke)
{
String pennies = "";
boolean output = false;
if( (ke.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER) )
{
pennies = et.getText().toString();
output = true;
}
System.out.println("output = " + output);
System.out.println("Pennies = " + pennies);
return output;
}
});
this.setContentView(sv);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.