2017-04-26 194 views
0

我想让用户输入文本到编辑文本。当用户点击输入键时,我想从编辑文本中获取文本并将其添加到我的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

请出示你的代码?很难猜测你的问题。 – Christopher

+0

我见过有人使用onKeyListeners和textWatchers。我只是想知道哪一个最容易使用,以及如何实现它。 –

+0

他们实际上做了不同的事情。 'OnKeyListener'将监听某些键盘按键,然后执行,另一方面'TextWatcher'只接收新文本,并且可能不会接收\ n字符,除非EditText被设置为多行。无论如何,我相信'OnKeyListener'是最好的方法。 –

回答

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行:IME ...

+0

我已经实现了这两个到我的代码和代码不执行时,输入按钮被击中 –

+0

显然你必须指定android :maxLines =“1”,否则它只是输入新的行命令。也许它与你使用的键盘有关,但如果你不需要多行edittext,我建议你以这种方式使用它。我测试过了,它似乎在我的最后工作。我编辑了答案 – bogdanN