Hot questions for Using Android EditText in keyboard

Question:

I'm trying to get an editTextview that only allows letters (lower- and uppercase).

It works with this code:

 edittv.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"));

The problem is that I get a numerical keyboard like this:

To go back to a normal keyboard I found this code:

edittv.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"));
edittv.setInputType(InputType.TYPE_CLASS_TEXT);

It works for getting the keyboard back but then all characters are allowed again, so it undo's the previous code.

So, how can I only allow letters with an alphabetical keyboard programatically.


Answer:

You can use this code below:

InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
        Spanned dest, int dstart, int dend) {
    for (int i = start; i < end; i++) {
        if (!Character.isLetter(source.charAt(i))&&!Character.isSpaceChar(source.charAt(i))) {
            return "";
        }
    }
    return null;
}
};
edit.setFilters(new InputFilter[] { filter });

Question:

I want to perform an action when enter is pressed in android editText. I have tried various ways of using EditorInfo.IME_ACTION_DONE, which works, but the problem is, it shows a tick icon, which I don't want. I want it to look like the default enter button on the keyboard.

How do I handle enter pressed event while retaining the "Enter" shape? Is there something like EditorInfo.IME_ACTION_ENTER to get my job done?

My approach (which shows tick icon):

editorEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
        if( (actionId == EditorInfo.IME_ACTION_DONE){
            Toast.makeText(EditorActivity.this, "working", Toast.LENGTH_SHORT).show();

            return true;
        }

        return false;
    }
});

I want it to look like "Enter" shape because I am making a text editor. I am trying to shift to another EditText on the "Enter" button is pressed and don't want it to look like a "Tick" button. That's why I don't want the tick symbol.


Answer:

I think just changing the inputType of your EditText in your layout should do the trick to have an "Enter" like button in your soft keyboard in Android.

<EditText
    android:id="@+id/edit"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:inputType="textMultiLine" />

Please note that I have used textMultiLine as the inputType of the EditText.

You can take some action on pressing the "Enter" button in your EditText like the following.

final EditText edittext = (EditText) findViewById(R.id.edit);

edittext.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (before == 0 && count == 1 && s.charAt(start) == '\n') {
            String text = edittext.getText().replace(start, start + 1, "").toString(); // Removes the enter
            Toast.makeText(MainActivity.this, text, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void afterTextChanged(Editable s) {
    }
});

Hope that completes the answer.

Question:

As the title says, I want to bring up the keyboard when I click/tap on the EditText. I've looked at other questions asking for the same thing but the answers just aren't working for me. I don't think the other questions are trying to do this in the onCreate() method and I don't think that they're using this answer for not focusing on the EditText when the app begins. I've added a list of code segments of what I tried and didn't work to avoid redundant answers.

MainActivity.java:

public class MainActivity extends ActionBarActivity {

    private boolean mIsPlaying;
    private int primesLE;
    private GridView mGridView;
    private ImageAdapter mAdapter;

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

        mIsPlaying = false;

        ViewGroup.LayoutParams layoutParams;

        primesLE = 0;
        int numOfColumns = (int)Math.round(Math.sqrt((double) primesLE));
        int numOfRows = (int)Math.ceil((double)primesLE/(double)numOfColumns);

        View relativeLayout = findViewById(R.id.relativeLayout);
        View title_horizontalScrollView = relativeLayout.findViewById(R.id.title_horizontalScrollView);
        View dataLayout = title_horizontalScrollView.findViewById(R.id.dataLayout);
        mGridView = (GridView) dataLayout.findViewById(R.id.mGridView);
        layoutParams = mGridView.getLayoutParams();
        layoutParams.width = 150*numOfColumns; //this is in pixels
        mGridView.setLayoutParams(layoutParams);
        mGridView.setNumColumns(numOfColumns);
        mAdapter = new ImageAdapter(this, android.R.layout.simple_list_item_1, primesLE);
        mGridView.setAdapter(mAdapter);

        View inputLayout = relativeLayout.findViewById(R.id.inputLayout);
        EditText inputEditText = (EditText)inputLayout.findViewById(R.id.inputEditText);

        //list of what doesn't work

        /*
        inputEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                }
            }
        });
        */
        /*
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(inputEditText, InputMethodManager.SHOW_IMPLICIT);
        */

        /*
        inputEditText.setFocusableInTouchMode(true);
        inputEditText.setFocusable(true);
        InputMethodManager imm = (InputMethodManager) MainActivity.this.getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(inputEditText.getWindowToken(), 0);
        inputEditText.requestFocus();
        imm.showSoftInput(inputEditText, 0);
        */
        /*        
            inputEditText.setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(
                    inputEditText.getWindowToken(), 0);
                return true;
            }

            });
         */   

    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    private void playSoE(){

        for(int i = 0; i < primesLE; i++){
            mAdapter.setPositionColor(i, 0xffff0000 + 0x100 * i);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        Log.d("Menu","Button Pressed");
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        else if (id == R.id.action_status){
            if(mIsPlaying) {
                mIsPlaying = false;
                item.setIcon(R.drawable.ic_action_play);
                item.setTitle("Play");
                playSoE();
            }
            else {
                mIsPlaying = true;
                item.setIcon(R.drawable.ic_action_pause);
                item.setTitle("Pause");
            }
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/relativeLayout"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/inputLayout"
        android:layout_alignParentTop="true"
        android:background="#a9a9a9"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:id="@+id/textView"
            android:text="All primes lower this number:"
            />

        <!-- Dummy item to prevent AutoCompleteTextView from receiving focus -->
        <LinearLayout
            android:focusable="true" android:focusableInTouchMode="true"
            android:layout_width="0px" android:layout_height="0px"/>

        <!-- :nextFocusUp and :nextFocusLeft have been set to the id of this component
             to prevent the dummy from receiving focus again -->
        <AutoCompleteTextView android:id="@+id/autotext"
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:nextFocusUp="@id/autotext" android:nextFocusLeft="@id/autotext"/>

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:inputType="numberSigned"
            android:ems="10"
            android:id="@+id/inputEditText"
            android:layout_weight="1" />
    </LinearLayout>


    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/inputLayout"

        android:id="@+id/title_horizontalScrollView"
        android:fillViewport="true">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".MainActivity"
            android:id="@+id/dataLayout"
            >

            <GridView
                android:id="@+id/mGridView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:columnWidth="90dp"
                android:verticalSpacing="10dp"
                android:horizontalSpacing="10dp"
                android:stretchMode="columnWidth"
                android:gravity="center"
                android:layout_alignParentBottom="true" />

        </RelativeLayout>

    </HorizontalScrollView>

</RelativeLayout>

ImageAdapter.java:

public class ImageAdapter extends ArrayAdapter {
    private Context mContext;
    private int mCount;
    private boolean setBlueBackground = false;
    private int[] gridColors;

    public ImageAdapter(Context c, int resource, int count) {
        super(c, resource);
        mContext = c;
        mCount = count;
        gridColors = new int[mCount];
        Arrays.fill(gridColors,Color.LTGRAY);
    }


    public int getCount() {
        return mCount;
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView textView;

        if (convertView == null) {
            // if it's not recycled, initialize some attributes
            textView = new TextView(mContext);
            textView.setGravity(Gravity.CENTER);
            textView.setLayoutParams(new GridView.LayoutParams(100, 100));

        } else {
            textView = (TextView) convertView;
        }


        textView.setBackgroundColor(gridColors[position]);

        textView.setText("" + position);
        return textView;
    }

    public void setPositionColor(int position, int color) {
        gridColors[position] = color;
        notifyDataSetChanged();
    }

}

menu_main.xml:

<?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/action_status"
        android:icon="@drawable/ic_action_play"
        android:title="Play"
        app:showAsAction="always"/>
    <item android:id="@+id/action_stop"
        android:icon="@drawable/ic_action_stop"
        android:title="Stop"
        app:showAsAction="always"/>
    <item android:id="@+id/action_settings"
            android:title="@string/action_settings"
            app:showAsAction="never"  />

    </menu>

P.S. I'm trying to bring up the keyboard with numbers only, and figure out how how to close it and execute it too.


Answer:

You are not seeing the inputEditText because the AutoCompleteTextView control is overlapping it. Try putting the inputEditText before the autotext and you will see the keyboard with numbers only. I also added android:orientation="vertical" to your XML.

 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/inputLayout"
        android:layout_alignParentTop="true"
        android:background="#a9a9a9"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:id="@+id/textView"
            android:text="All primes lower this number:"
            />

        <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="numberSigned"
        android:ems="10"
        android:id="@+id/inputEditText"/>

        <!-- Dummy item to prevent AutoCompleteTextView from receiving focus -->
        <LinearLayout
            android:focusable="true" android:focusableInTouchMode="true"
            android:layout_width="0px" android:layout_height="0px"/>

        <!-- :nextFocusUp and :nextFocusLeft have been set to the id of this component
             to prevent the dummy from receiving focus again -->
        <AutoCompleteTextView android:id="@+id/autotext"
                              android:layout_width="fill_parent" android:layout_height="wrap_content"
                              android:nextFocusUp="@id/autotext" android:nextFocusLeft="@id/autotext"/>


    </LinearLayout>

Question:

My EditText hint does not change when keyboard is in full screen mode. How can I fix this? Connecting... is the original hint. The hint does not change when the keyboard is in full screen. !!!

Here's my code:

public class MainActivity extends AppCompatActivity {

    EditText editText;

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

        final int intervalTime = 10000; // 10 sec
        Handler handler = new Handler();
        handler.postDelayed(new Runnable()  {
            @Override
            public void run() {

                editText = (EditText) findViewById(R.id.messageEditText);
                editText.setHint("new hint"); //set the new hint!

            }
        }, intervalTime);
    }
}

XML:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.me.myapplication.MainActivity">

    <EditText
        android:id="@+id/messageEditText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_weight="1"
        android:hint="Connecting..."
        android:inputType="text"
        android:textSize="15sp" />

</android.support.constraint.ConstraintLayout>

Answer:

Try to set android:imeOptions="flagNoExtractUi"

Question:

I'm trying to make a function for when the "<"/less than key is pressed, but i cant seem to get it correctly. I tried to add onKey(View view, int i, KeyEvent event) with Log, so that it would log everytime the "<" key was pressed but no matter what nothing is logged. I set the on key listener on my edit text but it doesnt work. Help Please. Is there anything i must add?

postingET = (EditText) findViewById(R.id.postInput); postingET.setOnKeyListener(new View.OnKeyListener() {
   @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
    Log.i("LOL", String.valueOf(view));
    return false;
    }
});

Answer:

postingET.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

Question:

I have a fragment with an EditText inside, I just want to open keyboard automatically when i arrive in this fragment but I can't find the way.

I think java provide a way to do this but can't find myself.

Thanks.


Answer:

you can request focus in onViewCreated()

.....
 @Override
 public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 
    EditText editText = view.findViewById(R.id.et);
    editText.requestFocus();
    InputMethodManager imgr = (InputMethodManager) 
    getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    imgr.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
...

Question:

I have an EditText with these values:

android:digits="0123456789"
android:inputType="numberDecimal"

As you see, I would like to insert only digits 0-9.

my problem is that when I reach the layout containing this EditText, the smartphone keyboard is displayed so it hides the screen before I can see the screen content. (although I didn't press on the edit text box!)

I would like the keyboard to be minimized as default.

I want that ONLY AFTER I press on the editText box, the keyboard will be displayed.

Is there any possibility to do so?


Answer:

Your EditText is gaining focus on activity load. To prevent this you can do as following:

METHOD 1: Add below attribute to your parent layout

android:focusableInTouchMode="true"

METHOD 2: In manifest add the following attribute to your activity inside activity tag:

android:windowSoftInputMode="stateAlwaysHidden"

Hope this helps.

Question:

In my MainActivity, I've added an EditText. When the user opens the app, the keyboard automatically shows up to let the user type text, but my app shows ads in onCreate(), therefore I want to disable that automatic event, is that possible?


Answer:

In the AndroidManifest.xml you can use the following settings:

<activity android:name="com.your.package.ActivityName" 
        android:windowSoftInputMode="stateHidden"  />

You can also try:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

You can find more details at this link.

Question:

Keyboard pushing content of edittext up when I start writing something , already add android:windowSoftInputMode="adjustResize" in AndroidManifest. Please provide solution for this issue.

Here is my code.

<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mouad.fixmyphone.fragment.SendUsFragment"
android:background="#ffff">

<!-- TODO: Update blank fragment layout -->


<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp">
    <View
        android:layout_width="fill_parent"
        android:layout_height="1dip"
        android:layout_below="@id/idtitle"
        android:background="#000000" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="E-mail :"
        android:textSize="20sp"
        android:textStyle="bold"
        android:textColor="#1A237E"
        android:layout_marginTop="90sp"
        android:id="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:text="SEND"
        android:textStyle="bold"
        android:layout_width="130sp"
        android:layout_height="wrap_content"
        android:id="@+id/sendbtn"
        android:textColor="#ffffff"
        android:background="@drawable/roundshapebtn"
        android:layout_marginTop="17dp"
        android:layout_below="@+id/msgtext"
        android:layout_centerHorizontal="true" />

    <EditText
        android:background="@drawable/rounded_edittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Your Problem in Short"
        android:textStyle="bold"
        android:id="@+id/msgtext"
        android:maxLength="80"
        android:maxLines="2"
        android:inputType="textMultiLine"
        android:layout_below="@+id/textmsgview"
        android:layout_alignParentLeft="true"
        android:drawableLeft="@drawable/ic_pb"
        android:layout_alignParentStart="true"
        android:drawablePadding="20dp"
        android:paddingLeft="1dp"
        android:paddingRight="12dp"
        android:paddingTop="12dp"
        android:paddingBottom="12dp"
        android:layout_marginTop="17dp"/>

    <EditText
        android:background="@drawable/rounded_edittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Your E-mail . . ."
        android:textStyle="bold"
        android:id="@+id/emailtext"
        android:inputType="textEmailAddress"
        android:drawableLeft="@drawable/ic_email"
        android:drawablePadding="20dp"
        android:paddingLeft="1dp"
        android:paddingRight="12dp"
        android:paddingTop="12dp"
        android:paddingBottom="12dp"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="17dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Tell us your problem :"
        android:textSize="20sp"
        android:textStyle="bold"
        android:textColor="#1A237E"
        android:layout_marginTop="20dp"
        android:id="@+id/textmsgview"
        android:layout_below="@+id/emailtext"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="8dp"
        android:layout_marginStart="8dp" />

</RelativeLayout>


Answer:

it seems like you use adjust_resize for the keyboard, the view will be "resized" to fit your view(i mean layout) if you dont want any resize, change to adjustPan

FYR Difference between adjustResize and adjustPan in android?