我是Android编程的新手,对于一般的编程比较新,所以请在这里跟我一起...
我正在尝试实现EditText字段,并且我在覆盖onKey时遇到问题。
我发现了一些错误并修复了它们但是当我编译时出现以下错误:
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
我尝试将onKey
方法移到内部类之外,但只有在我注释掉et.setOnKeyListener(...);
有人在另一个论坛中建议我删除OnKeyListener
和/或implements View.OnKeyListener
,但似乎应该可以实现该界面并使用OnKeyListener
....否则它的存在意义何在?
这是我的代码:
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;
}
});
}
}
答案 0 :(得分:1)
我不确定问题究竟是什么。我运行了这段代码,如果我在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);