处理在editText中按Enter键

时间:2017-04-26 13:57:03

标签: java android android-edittext

我试图让用户在编辑文本中输入文本。当用户点击回车键时,我想从编辑文本中获取文本并将其添加到我的ArrayList中。我在编辑文本中控制keyEvent时遇到问题。

public class MainActivity extends Activity {
ArrayList<String> array_list;
ListAdapter lv;
ListView list;
EditText edittext;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    array_list = new ArrayList<String>();
    edittext = (EditText) findViewById(R.id.textView);
    lv = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array_list);
    list = (ListView) findViewById(R.id.lstView);

    list.setAdapter(lv);
    edittext.requestFocus();

    edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            boolean handled = false;
            if (actionId == EditorInfo.IME_ACTION_GO) {
                array_list.add(edittext.getText().toString());
                edittext.setText("");
                edittext.requestFocus();
            }
            return handled;
        }
    });
}
}

所以我需要发生的是当用户按下enter时,它从字段中获取文本并将其添加到arrayList。然后它会删除文本字段中的文本并再次将其重点放置。

1 个答案:

答案 0 :(得分:2)

editText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    boolean handled = false;
    if (actionId == EditorInfo.IME_ACTION_GO) {
        //Perform your Actions here.

    }
    return handled;
   }
});`

在你的xml中你会做这样的事情      <EditText android:id="@+id/editText2" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text|textUri" android:imeOptions="actionGo" android:imeActionId="666" android:imeActionLabel="Some Label" android:maxLines="1"/>

关键是xml行包含android:ime ...

相关问题