0

I have a button "add" which adds input text from the editText into a listview below. However, can I make it possible to add text to the created list by simply pressing enter? If so, how can i do that in a simple manner?

Name=edittext, list =listview

@Override
        public void onClick(View view) {

            String name = Name.getText().toString();
            if (Name.length() > 0) {
                list.add(name);
                adapter.notifyDataSetChanged();
            }
        }
wp78de
  • 18,207
  • 7
  • 43
  • 71

3 Answers3

1

Quoted from : https://www.stackoverflow.com/a/6832095
Here is what you need to do to capture Enter event on editText :

final EditText edittext = (EditText) findViewById(R.id.edittext);
edittext.setOnKeyListener(new OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        // If the event is a key-down event on the "enter" button
        if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
            (keyCode == KeyEvent.KEYCODE_ENTER)) {
          // Perform action on key press
          Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
          return true;
        }
        return false;
    }
});
Anonymous
  • 2,184
  • 15
  • 23
  • It is better to flag the question as a duplicate of another question instead of copying an exact [answer](https://stackoverflow.com/a/6832095/7461132). @ShubhamSrivastava – Abhi Apr 06 '18 at 21:11
0

You need to overwrite your dispatchKeyEvent something like this

@Override
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
    Toast.makeText(UITestsActivity.this,
               "YOU CLICKED ENTER KEY",
                Toast.LENGTH_LONG).show();
        return true;
    }
    return super.dispatchKeyEvent(e);
};
Deepak kaku
  • 1,218
  • 9
  • 15
  • only i havnt used a dispatchkeyevent in my code. So do i just try the above without having used a dispatchkeyevent with my code so far? – Boris Cornelis Apr 06 '18 at 21:23
  • if you override this method then that particular activity will start listening to Enter key. so in the code above, instead of a Toast, get text from edittext and append it to the list or follow Shubham's answer – Deepak kaku Apr 06 '18 at 21:24
  • dispatchKeyEvent is a method of Activity. you should be able to override it by pressing (Ctrl+o) in Android Studio and look for dispatchKeyEvent method – Deepak kaku Apr 06 '18 at 21:29
  • still having trouble translating this to my specific code: – Boris Cornelis Apr 06 '18 at 21:31
  • do you mind sharing your activity code? I will try to modify my answer to your needs Also have a look here https://stackoverflow.com/questions/28593286/android-edittext-enter-key-listener – Deepak kaku Apr 06 '18 at 21:36
0

Too long for a comment, therefore adding an answer. Building over previous answer, to achieve your function use this code:

import android.app.LauncherActivity;
import android.content.Context;
import android.content.Intent;
import android.hardware.input.InputManager;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.view.KeyEvent;

import java.util.ArrayList;

public class LoginPage extends AppCompatActivity {

    EditText Name;
    Button Add;
    ListView Lv;
    Button Reset;
    Button Sgame;

    private ImageView information;
    private PopupWindow popupWindow;
    private LayoutInflater layoutInflater;
    private RelativeLayout relativeLayout;

    ArrayList<String> list = new ArrayList<String>();
    ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_page);

        Name = (EditText) findViewById(R.id.Playername);
        Add = (Button) findViewById(R.id.Addbutton);
        Lv = (ListView) findViewById(R.id.list);
        Reset = (Button) findViewById(R.id.Resetbutton);
        Sgame = (Button) findViewById(R.id.Startgamebutton);

        information = (ImageView) findViewById(R.id.info);
        relativeLayout = (RelativeLayout) findViewById(R.id.constrain);

        adapter = new ArrayAdapter<String>(this, R.layout.listviewlayout, R.id.list_content, list);
        Lv.setAdapter(adapter);


        final EditText Name = (EditText) findViewById(R.id.Playername);
        class MyKeyListener implements View.OnKeyListener {
            @Override
            public boolean onKey (View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                        (keyCode == KeyEvent.KEYCODE_ENTER)) {

                    String name = Name.getText().toString();
                    if (Name.length() > 0) {
                        list.add(name);
                        adapter.notifyDataSetChanged();
                    }
                        return true;
                    }
                return false;
                }

        }
        Name.setOnKeyListener(new MyKeyListener());

        Add.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                String name = Name.getText().toString();
                if (Name.length() > 0) {
                    list.add(name);
                    adapter.notifyDataSetChanged()
                    ;
                }
            }
        });

        Reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.clear();

            }
        });

        Sgame.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!list.isEmpty())
                    openActivity2();
            }
        });

        information.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
                ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.informationpopup, null);

                popupWindow = new PopupWindow(container, 1150, 2000, true);
                popupWindow.showAtLocation(relativeLayout, Gravity.NO_GRAVITY, 140, 300);

                container.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View view, MotionEvent motionEvent) {
                        popupWindow.dismiss();
                        return true;
                    }
                });

            }
        });
    }

    public void openActivity2() {
        Intent intent = new Intent(this, Gamescreen.class);
        String s= list.get(0);
        intent.putExtra("Name1", s);
        startActivity(intent);
    }}
Abhi
  • 3,431
  • 1
  • 17
  • 35
  • only here youve removed the add button possibility to add the edit text to the listview, however i want to both make it possibly through enter, or through pressing the add button – Boris Cornelis Apr 06 '18 at 22:23
  • Okay so add the button feature back. I've added the feature by `ENTER` key in the above code. Refer it and add the button feature back again. – Abhi Apr 06 '18 at 22:26
  • Oke lets see: https://gyazo.com/447ed3ab3ac67e566dd8b59d36e81277. Few red lines unrecognised commands. Left the button feature in it now. – Boris Cornelis Apr 06 '18 at 22:34
  • You need to import the class KeyEvent: `import android.view.KeyEvent;`. Just hover over the red line and you will see an option to correct imports by pressing Alt+Enter. – Abhi Apr 06 '18 at 22:44
  • alright @Abhi, Ive added this (resolved the red lines) now I just have a compliation error (Just posted updated code as an answer) – Boris Cornelis Apr 06 '18 at 23:00
  • What error do you receive? Post your stacktrace. Also edit your original question and post your results instead of posting new answers. It is creating too much noise in the whole post – Abhi Apr 06 '18 at 23:03
  • Check the edited answer. I have corrected your code and it works now. – Abhi Apr 07 '18 at 05:36
  • Only problems I still have is that the keyboard appears immediately upon start up (rather i want it to appear when clicking on the edit text field -> likewise dissapear on enter click/add button). https://gyazo.com/c870f868424dc40e79bf1ee5f2c3c74a. Secondly when you type in a name and add through enter or add button the entered name remains in the edit text field (I really want it to clear after adding and make it say player ... in the field again -> see image: https://gyazo.com/2673d1903015e718db5588d2ee188a17. Is it possible you can help me with this. Im asking a lot im sorry :( – Boris Cornelis Apr 07 '18 at 05:58
  • Post a new question and I will surely help. This is because the original question has been answered and future users may get confused with the extra code. – Abhi Apr 07 '18 at 06:03