我正在尝试为 android ime 选项设置一个监听器,该监听器将 EditText
的值存储在共享首选项中。我已将其设置为这样,但是当我按键盘上的“返回”键时,没有任何反应,并且它永远不会进入监听器。关于我为什么做错的任何想法?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mDone = (Button) findViewById(R.id.done);
mTemperature = (EditText) findViewById(R.id.temperature);
mDone.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
int action = event.getAction();
if (actionId == EditorInfo.IME_ACTION_DONE) {
// Do whatever you want here
SharedPreferences preferences = getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor edit = preferences.edit();
int updateSweater = Integer.parseInt(mTemperature.getText().toString());
edit.remove("sweater");
edit.putInt("sweater", updateSweater);
edit.commit();
preferences.getInt("sweater", 0);
Toast.makeText(SettingsActivity.this, "Sweater Weather Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SettingsActivity.this, MainActivity.class);
startActivity(intent);
return true;
}
return false;
}
});
}
这就是我设置 EditText 的方式
<EditText
android:id="@+id/temperature"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/white"
android:textColorHint="@color/gray"
android:textSize="25sp"
android:layout_centerHorizontal="true"
android:hint="Farenheit"
android:inputType="phone"
android:imeOptions="actionDone"/>
最佳答案
我相信它不起作用,因为 setOnEditorActionListener
应该定义到您的 EditText
(而不是您的 Button)。
mTemperature = (EditText) findViewById(R.id.temperature);
mTemperature.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
int action = event.getAction();
if (actionId == EditorInfo.IME_ACTION_DONE) {
// Do whatever you want here
SharedPreferences preferences = getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor edit = preferences.edit();
int updateSweater = Integer.parseInt(mTemperature.getText().toString());
edit.remove("sweater");
edit.putInt("sweater", updateSweater);
edit.commit();
preferences.getInt("sweater", 0);
Toast.makeText(SettingsActivity.this, "Sweater Weather Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SettingsActivity.this, MainActivity.class);
startActivity(intent);
return true;
}
return false;
}
});
如果您需要在mDone
中点击后执行任何操作,最好为mDone
设置一个ClickListener
关于Android ime 选项不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38415963/