我打开键盘上的按钮点击,我将所有按键值存储在字符串中,但我遇到了这样的问题
1. when i press CAPITAL keys then i will got 2 times char
2. when i press search and Menu button then also enter the key
3. some char i can't get like PIE
所以请检查此代码并给我正确的答案。 我的代码是:
package com.indianic.phykeyboard;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class KeyboardActivity extends Activity {
EditText mEdit;
Boolean key = false;
Button mKey, mMon;
String getvalue;
InputMethodManager imm;
StringBuilder stringBuilder;
TextView value;
String ch = "";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mKey = (Button) findViewById(R.id.openkey);
value = (TextView) findViewById(R.id.value);
mKey.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, 0);
stringBuilder = new StringBuilder();
}
});
}
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
return true;
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.v("log_tag", "char : " + event.getUnicodeChar());
if (event.getUnicodeChar() != 0) {
int i = event.getUnicodeChar();
ch = new Character((char) i).toString();
}
if (ch.length() > 0) {
if (keyCode == KeyEvent.KEYCODE_DEL && stringBuilder.length() >= 1) {
stringBuilder.delete(stringBuilder.length() - 1, stringBuilder
.length());
} else if (keyCode != KeyEvent.KEYCODE_DEL
&& keyCode != KeyEvent.KEYCODE_ENTER) {
stringBuilder.append(ch);
} else if (keyCode == KeyEvent.KEYCODE_SEARCH
|| keyCode == KeyEvent.KEYCODE_MENU) {
}
}
if (keyCode == KeyEvent.KEYCODE_BACK) {
stringBuilder.delete(0, stringBuilder.length());
finish();
}
String str = stringBuilder.toString().trim();
value.setText(str);
return false;
}
}
答案 0 :(得分:2)
你可以试试这段代码:
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.v("log_tag", "char : " + event.getUnicodeChar());
if (event.getUnicodeChar() != 0) {
int i = event.getUnicodeChar();
ch += new Character((char) i).toString();
}
if (keyCode == KeyEvent.KEYCODE_DEL && ch.length() > 0) {
ch = ch.substring(0, ch.length() - 1);
}
value.setText(ch);
return super.onKeyDown(keyCode, event);
}
答案 1 :(得分:1)
if (event.getUnicodeChar() != 0) {
int i = event.getUnicodeChar();
ch = new Character((char) i).toString();
}
这部分例程正在丢失数据。 char
无法包含所有可用的Unicode代码点。我不知道这是否与给你麻烦的东西有关,但它表明你没有正确地做事并试图修补你的错误可能是一个错误 - 修复这将需要更根本的改造你的事件处理程序,至少。