我希望构建一个页面并包含一个文本框。一旦用户使用键盘并添加一些字符并按下Android键盘上的Enter按钮,它将返回一个toast。我学习教程,我知道我应该使用keyevent,我发现了问题:1)无法解析符号" OnKeyListener"和" text.setOnKeyListener(本);"表示"在视图中无法应用于"似乎keylistener没有正确使用,我无法弄明白。 THX
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnKeyListener {
private ScrollView mScrollView;
protected EditText text;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (EditText)findViewById(R.id.text1);
text.setOnKeyListener(this);
}
@Override
public boolean onKeyDown(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
//mScrollView.smoothScrollBy(0, 500);
Toast.makeText(getApplicationContext(), "Enter!", Toast.LENGTH_LONG).show();
Log.d("msg","*****************%%%%%%%%%%%%%%%%%%@@@@@@@@@");
}
return super.onKeyDown(keyCode, event);
}
}
答案 0 :(得分:2)
View.OnKeyListener
是interface
类的内部View
。使用如下。
public class MainActivity extends Activity implements View.OnKeyListener {
private ScrollView mScrollView;
protected EditText text;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (EditText) findViewById(R.id.text1);
text.setOnKeyListener(this);
}
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
return false;
}
}
答案 1 :(得分:1)
指定您希望View
事件onKeyDown()
。
text.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_ENTER:
Toast.makeText(getApplicationContext(), "Enter!", Toast.LENGTH_LONG).show();
Log.d("msg","*****************%%%%%%%%%%%%%%%%%%@@@@@@@@@");
break;
default:
return false;
}
return true;
}
});