In my Android application, I want an EditText with android:editable="false" but the cursor blinking. The cursor blinking seems doesn't work after "editable" is set to false.
I just want to use my own Keyboard widget(not the system's soft keyboard), and keep the cursor blinking.
Is there any idea to make that possible?
Maybe try leaving out the xml attribute android:editable entirely and then try the following in combination to
keep the cursor blinking and prevent touch events from popping up a native IME(keyboard)..
/*customized edittext class
* for being typed in by private-to-your-app custom keyboard.
* borrowed from poster at http://stackoverflow.com/questions/4131448/android-how-to-turn-off-ime-for-an-edittext
*/
public class EditTextEx extends EditText {
public EditTextEx(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onCheckIsTextEditor() {
return false; //for some reason False leads to cursor never blinking or being visible even if setCursorVisible(true) was called in code.
}
}
Step 2
change the above method to say return true;
Step 3
Add another method to above class.
#Override
public boolean isTextSelectable(){
return true;
}
Step 4
In the other location where the instance of this class has been instantiated and called viewB I added a new touch event handler
viewB.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
viewB.setCursorVisible(true);
return false;
}
});
Step 5 Check to make sure XML and or EditText instantiation code declares IME/keyboard type to be 'none'. I didnt confirm relevance, but Im also using the focusable attributes below.
<questionably.maybe.too.longofa.packagename.EditTextEx
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:focusable="true"
android:focusableInTouchMode="true"
android:inputType="none">
Sorry for so many xml attributes. My code uses them all, testing in 4.2.1, and has results.
Hope this helps.
You can use either the xml attribute
android:cursorVisible="false"
or the java function
setCursorVisible(false).
it will work
Just Adding this method for anyone looking for and answer. I have tried many methods but only this one worked from me.
public static void disableSoftKeyboard(final EditText v) {
if (Build.VERSION.SDK_INT >= 11) {
v.setRawInputType(InputType.TYPE_CLASS_TEXT);
v.setTextIsSelectable(true);
} else {
v.setRawInputType(InputType.TYPE_NULL);
v.setFocusable(true);
}
}
I called the following from onCreate(), but this affects all EditTexts.
private void hideKeyboard ()
{
getWindow ().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
getWindow ().setFlags (WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
}
Related
I am working on Android Smart TV application:
In a view there is a custom keyboard and an EditText.
When application launches focus goes to the keyboard.
Desired:
When the user types with keyboard (clicking with a remote) the cursor should also blink inside the editText.
How can I show this effect inside the EditText?
This happens if you set a background for the field. If you want to solve this, set the cursorDrawable to #null.
You should add textCursorDrawable with cursorVisible.
Reference to a drawable that will be drawn under the insertion cursor.
android:cursorVisible="true"
android:textCursorDrawable="#null"
You could try something like this:
editText.setText(text);
editText.setPressed(true);
editText.setSelection(editText.getText().length()); // moves the cursor to the end of the text
However, there are 2 problems with this approach:
The cursor will not blink. The logic for the blinking is in the Editor class and cannot be overridden. It requires that the EditText is focused, and only 1 View can be focused at once within a Window - in your case that will be one of the keyboard buttons.
/**
* #return True when the TextView isFocused and has a valid zero-length selection (cursor).
*/
private boolean shouldBlink() {
if (!isCursorVisible() || !mTextView.isFocused()) return false;
...
}
The cursor will not always be visible. The blinking of the cursor is based on the System time - it is visible for half a second, and hidden for the next half a second. The cursor will only be visible if the code I suggested above is called at a point in time when the cursor would be visible according to the System time.
This is why the native keyboard/IME works the way it does. It is a separate Window that allows the EditText to maintain focus and have the blinking cursor functionality, while the user is tapping on Views in a different Window (the keyboard/IME).
That being said, there is a workaround for the problems above - make sure to set shouldBlink to false when you no longer need it though, it's a guaranteed memory leak or crash otherwise:
private void blink() {
if (shouldBlink) {
editText.setText(editText.getText());
editText.setPressed(true);
editText.setSelection(editText.getText().length());
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (shouldBlink) {
blink();
}
}
}, 500);
}
}
You can do this..I hope/think that u have a layout for the buttons u have created, by this u can set a Focus Listener for that layout and inside the onFocusChange method you can check if(layout.hasFocus()) and do this...
For example if your editText is named as et, u can set this to it:
et.setActivated(true);
et.setPressed(true);
I have a small example code for you having two edit text
et2.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(et2.hasFocus()){
//et1.setCursorVisible(true);
et1.setActivated(true);
et1.setPressed(true);
}
}
});
In your layout xml file add the following line in your edit text:
<requestFocus/>
This will place the cursor in your editText widget.
Hope it helps.
simply add
editText.requestFocus();
There is a couple of ways doing it:
1) XML
android:cursorVisible="true"
2) Java
mEditText.setOnClickListener(editTextClickListener);
OnClickListener editTextClickListener = new OnClickListener() {
public void onClick(View v) {
if (v.getId() == mEditText.getId()) {
mEditText.setCursorVisible(true);
}
}
};
or
if (mEditText.hasFocus()){
mEditText.setCursorVisible(true);
}
I know this is necro, but this was much better than the solutions above. Just extend EditText and add:
#Override
public boolean isCursorVisible() {
return true;
}
#Override
public boolean isFocused() {
return true;
}
And in your XML:
<com.foo.MyEditText
...
android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="false"
android:cursorVisible="true"/>
Now the EditText thinks it is focused and the cursor is visible, but it actually can't be focused.
private void setFocusCursor(){
mBinding.replyConversationsFooter.footerEditText.setFocusable(true);
`mBinding.replyConversationsFooter.footerEditText.setFocusableInTouchMode(true);`
`mBinding.replyConversationsFooter.footerEditText.requestFocus();`
}
Just call this function in oncreateView() and there you go.
We can only set one and only focus on a window.So doing this will help you solve your problem.
You can use the following code in your Activity:
//Get the EditText using
EditText et = (EditText)findViewById(R.id.editText);
//Set setCursorVisible to true
et.setCursorVisible(true);
You can explicitly put caret to last position in text:
int pos = editText.getText().length();
editText.setSelection(pos);
This will always focus on first character on edittext.
android:focusable="true"
Tested on API 27, 28 emulator.
Remove a background attribute, add focusable:
<EditText
...
android:focusable="true"
android:focusableInTouchMode="true"
/>
In code write: edit.requestFocus(); Though an underline will be visible.
In order to remove an underline, see https://stackoverflow.com/a/52052087/2914140:
edit.getBackground().mutate().setColorFilter(ContextCompat.getColor(getContext(), R.color.white), PorterDuff.Mode.SRC_ATOP);
To change a color of the cursor see https://stackoverflow.com/a/49462015/2914140:
add android:textCursorDrawable="#drawable/shape_cursor", while shape_cursor is:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<size
android:width="1dp"
android:height="25dp"
/>
<solid android:color="#color/gray" />
</shape>
It works on API 27, 28 emulator, but on a real device (API 21) cursor disappears. I tried many variants from here and there, but nothing helped.
Then I noticed that when EditText contains at least one symbol, it shows cursor. I added a TextWatcher to add a space when nothing entered.
private lateinit var someText: String
...
edit.requestFocus()
edit.setText(" ")
edit.addTextChangedListener(YourTextWatcher())
private inner class YourTextWatcher : TextWatcher {
override fun afterTextChanged(s: Editable?) {
someText = s.toString().trim()
if (someText.isEmpty()) {
// To not fall into infinite loop.
if (s?.length != 1) {
edit.setText(" ")
}
} else {
}
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
}
Also you can add paddings in order to tap inside EditText, if it is small.
I did like this:
var msgEditText = dialog.findViewById(R.id.msg1textView) as EditText
msgEditText.isActivated = true
msgEditText.isPressed = true
msgEditText.requestFocus()
msgEditText.setSelection(view.getText().length)
I have a fragment within a TabHost that has multiple text fields in it. The virtual keyboard works just fine to enter text into using inputType set, but the hardware keyboard (on Droid, Droid 2, etc) does not work.
From my testing as soon as you start typing on the hardware keyboard, the EditText loses focus and the "typing" seems to go elsewhere in the application. I have tried both configurations below:
<EditText
android:id="#+id/editTextPlusFat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.15"
android:background="#drawable/textfield_default_holo_light"
android:digits="0123456789."
android:ems="10"
android:hint="#string/str_CalcHintFat"
android:inputType="number" >
AND
<EditText
android:id="#+id/editTextPlusFat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.15"
android:background="#drawable/textfield_default_holo_light"
android:ems="10"
android:hint="#string/str_CalcHintFat"
android:inputType="numberDecimal" >
Does anyone have any ideas why this happens? Thank you.
My solution was to add onTouchListener() to all EditTexts in each Fragment - see below.
OnTouchListener foucsHandler = new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
arg0.requestFocusFromTouch();
return false;
}
};
currentActivity.findViewById(R.id.editTextPlusServings).setOnTouchListener(foucsHandler);
currentActivity.findViewById(R.id.editTextPlusFoodName).setOnTouchListener(foucsHandler);
As in the duplicate question, the better answer is to remove the focus switching by overriding onTouchModeChanged() from TabHost.
Add a new class extending TabHost:
package net.lp.collectionista.ui.views;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TabHost;
public class BugFixedTabHost extends TabHost {
public BugFixedTabHost(Context context, AttributeSet attrs) {
super(context, attrs);
}
public BugFixedTabHost(Context context) {
super(context);
}
#Override
public void onTouchModeChanged(boolean isInTouchMode) {
// leave it empty here. It looks that when you use hard keyboard,
// this method would have be called and the focus will be taken.
}
}
In your Fragment (or Activity) replace the TabHost type with BugFixedTabHost.
Finally, assuming you use TabHost in layout xmls too, change it to your custom view (full package name):
<net.lp.collectionista.ui.views.BugFixedTabHost
android:id="#android:id/tabhost" ...
I'm not sure why this did not work for #mattdonders, but this is the right way to go. And it is cheaper than attaching listeners to every EditText. By the way, have we figured out yet why mCurrentView.hasFocus() is False or so?
So I've got what seems to be a common problem, which is that the EditText in my dialog box doesn't show up when it gets focus. I've seen several workarounds, such as in this thread, this one and this one (and many more), but I have never seen a satisfactory explanation for why this is happening in the first place.
I would much prefer to have android use its own default behavior for EditTexts than to build my own, but it seems like everyone (in those threads) has accepted that the default behavior for EditTexts in Dialogs is to just give a cursor and no keyboard. Why would that be?
For the record, none of these workarounds seem to be working for me - the closest I've been able to come is forcing a keyboard to appear underneath the dialog box (using InputMethodManager.toggleSoftKeyboard(*)). My particular configuration is API15, the EditText shows up in a footer on a ListView within an AlertDialog. The EditText android:focusable="true" is set, and onFocusChangeListener is receiving focus events.
Edit:
As requested, here is the specific code snippet that I'm working with. I won't bother with the whole layout, but in this specific application, the EditText appears in response to pressing a button on the dialog (similar to an action view). It is contained in a RelativeLayout which by default has visibility "gone":
<RelativeLayout
android:id="#+id/relLay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:visibility="gone"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp">
<ImageButton
android:id="#+id/cancelBut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="#color/transparent"
android:src="#drawable/cancelButton"
android:layout_margin="5dp"/>
<ImageButton
android:id="#+id/okBut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/cancelBut"
android:background="#color/transparent"
android:src="#drawable/okButton"
android:layout_margin="5dp" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:focusable="true"
android:layout_toLeftOf="#id/okBut"/>
</RelativeLayout>
The code which builds this sets the visibility of the relativeLayout to "Visible" (and hides the other UI elements). This should be enough to pull up the keyboard when the EditText gets focused, based on my experience with EditText. However, for some reason this is not the case. I can set the following onFocusChangeListener:
edit_text.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// For whatever reason we need to request a soft keyboard.
InputMethodManager imm = (InputMethodManager)dlg.getWindow().getContext().getSystemService(_Context.INPUT_METHOD_SERVICE);
if(hasFocus)
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
Log.v("DialogProblem", "Focus requested, " + (hasFocus?"has focus.":"doesn't have focus."));
}
}
});
Using this configuration, when I first enter the EditText, the onFocusChangedListener triggers, and generates a log that invariably looks like this:
Focus requested, has focus.
Focus requested, doesn't have focus.
Focus requested, has focus.
The keyboard shows up and then disappears, probably because I toggle it twice, but even when I make sure it stays up, it's behind the dialog window (in a greyed out area), and there's no way to get to it without closing the dialog.
That said, I'd like to emphasize that even though I may be able to get this work-around to work, I'm primarily interested in finding a simple reason why the EditText isn't triggering in the first place, and why this seems to be so commonplace!
OK, so after reading a lot, I have figured out why this is a problem, and I do not need to use any workarounds.
The problem seems to be (at least in my case), that since the place where you enter text is hidden initially (or nested or something), AlertDialog is automatically setting the flag WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM (or some combination of that and WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) so that things don't trigger a soft input to show up.
The way that I've found to fix this is to add the following line after the dialog has been created:
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
Once this is done, the EditText acts like a normal EditText, no kludges or workarounds necessary.
I have the same problem in my own app. If you are developing for API level >= 8 you can use this snippet:
dialog.setOnShowListener(new OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(textEdit, InputMethodManager.SHOW_IMPLICIT);
}
});
I haven't found a solution for lower API levels...
BTW: This snippet doesn't always work on emulator. I don't know why.
If you read the AlertDialog documentation you'll find there:
The AlertDialog class takes care of automatically setting *WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM* for you based on whether any views in the dialog return true from View.onCheckIsTextEditor(). Generally you want this set for a Dialog without text editors, so that it will be placed on top of the current input method UI. You can modify this behavior by forcing the flag to your desired mode after calling onCreate.
I had the problem you've mentioned with EditText in ListView inside a Dialog. I fixed it by overwriting the custom view class (in my case ListView) with my own FocusableListView, with just one method overwritten:
public class FocusableListView extends ListView {
public FocusableListView(Context context) {
super(context);
}
public FocusableListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FocusableListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public boolean onCheckIsTextEditor() {
// this is where the magic happens
return true;
}
}
Then I'm using it in the layout file as:
<?xml version="1.0" encoding="UTF-8"?>
<com.myexample.wiget.FocusableListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:descendantFocusability="beforeDescendants"
android:layout_height="wrap_content" />
You can overwrite the RelativeLayout in your case the same way and it should work.
This is what worked for me. Create the AlertDialog.Builder, set title, positiveButton, negativeButton. After do this:
AlertDialog dialog = builder.create();
dialog.getWindow().clearFlags( WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
dialog.show();
editText.requestFocus();
You don't need to use builder.show();.
The code above is very helpfull. But you must call the "show" method after the "create" method (I don't know why, but only this works in my dialog with EditText in ListView).
In method onCreateDialog:
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case YOUR_DIALOG_ID: {
//...
AlertDialog a = new AlertDialog.Builder(this)./*
... set the properties here
*/
.create();
a.show(); //!!! this is very important to call the "show" method
a.getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
return a;
}
//...
}
return null;
}
Thank you! I have an embedded TextEdit in the last row of ListView embedded in the alert dialog fragment. I used your solution of clearing the flags as a post runnable and now it works perfectly.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("My Title");
m_adapter = new MyAdapter(getContext());
builder.setAdapter(m_adapter, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
final AlertDialog dialog = builder.create();
final ListView listView = dialog.getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
listView.post(new Runnable() {
#Override
public void run() {
dialog.getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
}
});
return dialog;
}
Here's one way to do it:
final Window dialogWindow = dialog.getWindow();
dialogWindow.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
I would like to add on to Paul's answer and Alexander's comment.
I myself have a dialog that's created in the onCreateDialog() method, which (seems to) require returning dialog.show();, wherefore you can not add the layoutparams to the dialog where the dialog is created. To work around this, just keep your onCreateDialog() method the same, and add an onResume() method as follows:
#Override
public void onResume() {
super.onResume();
Dialog dialog = getDialog();
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}
This should do the trick, it works for me, thankfully. Have been on this case for quite some while.
full code for showing the keyboard in dialog:
public void onFocusChange(View v, boolean hasFocus) {
Log.v("onFocusChange", hasFocus + " " + showkeyboard);
if (hasFocus) {
if (showkeyboard++ == 0) {
alertDialog.getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
alertDialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
} else {
showkeyboard = 1;
}
}
}
This worked for me ----
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
//dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
//dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
InputMethodManager mgr = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.showSoftInput(v, InputMethodManager.SHOW_FORCED);
editText.setFocusable(true);
}
});
just add below codeLine:
// to show keyboard automatically while editText is in dialog
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
I like my UIs to be intuitive; each screen should naturally and unobtrusively guide the user on to the next step in the app. Barring that, I strive to make things as confusing and confounding as possible.
Just kidding :-)
I've got three TableRows, each containing a read-only and non-focusable EditText control and then a button to its right. Each button starts the same activity but with a different argument. The user makes a selection there and the sub-activity finishes, populating the appropriate EditText with the user's selection.
It's the classic cascading values mechanism; each selection narrows the available options for the next selection, etc. Thus I'm disabling both controls on each of the next rows until the EditText on the current row contains a value.
I need to do one of two things, in this order of preference:
When a button is clicked, immediately remove focus without setting focus to a different button
Set focus to the first button when the activity starts
The problem manifests after the sub-activity returns; the button that was clicked retains focus.
Re: #1 above - There doesn't appear to be a removeFocus() method, or something similar
Re: #2 above - I can use requestFocus() to set focus to the button on the next row, and that works after the sub-activity returns, but for some reason it doesn't work in the parent activity's onCreate().
I need UI consistency in either direction--either no buttons have focus after the sub-activity finishes or each button receives focus depending on its place in the logic flow, including the very first (and only) active button prior to any selection.
Using clearFocus() didn't seem to be working for me either as you found (saw in comments to another answer), but what worked for me in the end was adding:
<LinearLayout
android:id="#+id/my_layout"
android:focusable="true"
android:focusableInTouchMode="true" ...>
to my very top level Layout View (a linear layout). To remove focus from all Buttons/EditTexts etc, you can then just do
LinearLayout myLayout = (LinearLayout) activity.findViewById(R.id.my_layout);
myLayout.requestFocus();
Requesting focus did nothing unless I set the view to be focusable.
Old question, but I came across it when I had a similar issue and thought I'd share what I ended up doing.
The view that gained focus was different each time so I used the very generic:
View current = getCurrentFocus();
if (current != null) current.clearFocus();
You can use View.clearFocus().
Use View.requestFocus() called from onResume().
android:descendantFocusability="beforeDescendants"
using the following in the activity with some layout options below seemed to work as desired.
getWindow().getDecorView().findViewById(android.R.id.content).clearFocus();
in connection with the following parameters on the root view.
<?xml
android:focusable="true"
android:focusableInTouchMode="true"
android:descendantFocusability="beforeDescendants" />
https://developer.android.com/reference/android/view/ViewGroup#attr_android:descendantFocusability
Answer thanks to:
https://forums.xamarin.com/discussion/1856/how-to-disable-auto-focus-on-edit-text
About windowSoftInputMode
There's yet another point of contention to be aware of. By default,
Android will automatically assign initial focus to the first EditText
or focusable control in your Activity. It naturally follows that the
InputMethod (typically the soft keyboard) will respond to the focus
event by showing itself. The windowSoftInputMode attribute in
AndroidManifest.xml, when set to stateAlwaysHidden, instructs the
keyboard to ignore this automatically-assigned initial focus.
<activity
android:name=".MyActivity"
android:windowSoftInputMode="stateAlwaysHidden"/>
great reference
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/ll_root_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
LinearLayout llRootView = findViewBindId(R.id.ll_root_view);
llRootView.clearFocus();
I use this when already finished update profile info and remove all focus from EditText in my layout
====> Update: In parent layout content my EditText add line:
android:focusableInTouchMode="true"
What about just adding android:windowSoftInputMode="stateHidden" on your activity in the manifest.
Taken from a smart man commenting on this: https://stackoverflow.com/a/2059394/956975
I tried to disable and enable focusability for view and it worked for me (focus was reset):
focusedView.setFocusable(false);
focusedView.setFocusableInTouchMode(false);
focusedView.setFocusable(true);
focusedView.setFocusableInTouchMode(true);
First of all, it will 100% work........
Create onResume() method.
Inside this onResume() find the view which is focusing again and again by findViewById().
Inside this onResume() set requestFocus() to this view.
Inside this onResume() set clearFocus to this view.
Go in xml of same layout and find that top view which you want to be focused and set focusable true and focusableInTuch true.
Inside this onResume() find the above top view by findViewById
Inside this onResume() set requestFocus() to this view at the last.
And now enjoy......
android:focusableInTouchMode="true"
android:focusable="true"
android:clickable="true"
Add them to your ViewGroup that includes your EditTextView.
It works properly to my Constraint Layout. Hope this help
You could try turning off the main Activity's ability to save its state (thus making it forget what control had text and what had focus). You will need to have some other way of remembering what your EditText's have and repopulating them onResume(). Launch your sub-Activities with startActivityForResult() and create an onActivityResult() handler in your main Activity that will update the EditText's correctly. This way you can set the proper button you want focused onResume() at the same time you repopulate the EditText's by using a myButton.post(new Runnable(){ run() { myButton.requestFocus(); } });
The View.post() method is useful for setting focus initially because that runnable will be executed after the window is created and things settle down, allowing the focus mechanism to function properly by that time. Trying to set focus during onCreate/Start/Resume() usually has issues, I've found.
Please note this is pseudo-code and non-tested, but it's a possible direction you could try.
You do not need to clear focus, just add this code where you want to focus
time_statusTV.setFocusable(true);
time_statusTV.requestFocus();
InputMethodManager imm = (InputMethodManager)this.getSystemService(Service.INPUT_METHOD_SERVICE);
imm.showSoftInput( time_statusTV, 0);
Try the following (calling clearAllEditTextFocuses();)
private final boolean clearAllEditTextFocuses() {
View v = getCurrentFocus();
if(v instanceof EditText) {
final FocusedEditTextItems list = new FocusedEditTextItems();
list.addAndClearFocus((EditText) v);
//Focus von allen EditTexten entfernen
boolean repeat = true;
do {
v = getCurrentFocus();
if(v instanceof EditText) {
if(list.containsView(v))
repeat = false;
else list.addAndClearFocus((EditText) v);
} else repeat = false;
} while(repeat);
final boolean result = !(v instanceof EditText);
//Focus wieder setzen
list.reset();
return result;
} else return false;
}
private final static class FocusedEditTextItem {
private final boolean focusable;
private final boolean focusableInTouchMode;
#NonNull
private final EditText editText;
private FocusedEditTextItem(final #NonNull EditText v) {
editText = v;
focusable = v.isFocusable();
focusableInTouchMode = v.isFocusableInTouchMode();
}
private final void clearFocus() {
if(focusable)
editText.setFocusable(false);
if(focusableInTouchMode)
editText.setFocusableInTouchMode(false);
editText.clearFocus();
}
private final void reset() {
if(focusable)
editText.setFocusable(true);
if(focusableInTouchMode)
editText.setFocusableInTouchMode(true);
}
}
private final static class FocusedEditTextItems extends ArrayList<FocusedEditTextItem> {
private final void addAndClearFocus(final #NonNull EditText v) {
final FocusedEditTextItem item = new FocusedEditTextItem(v);
add(item);
item.clearFocus();
}
private final boolean containsView(final #NonNull View v) {
boolean result = false;
for(FocusedEditTextItem item: this) {
if(item.editText == v) {
result = true;
break;
}
}
return result;
}
private final void reset() {
for(FocusedEditTextItem item: this)
item.reset();
}
}
I've opened a bug but i was wondering if anyone encountered this issue and knows a workaround.
If you define a text view with a hint inside it, give it right gravity (android:gravity="right") then if you define android:singleLine=true or android:maxLines="1" or android:scrollHorizonatally="true" you don't see the hint. removing the right gravity returns the hint to the left side, removing all the tree params i mentioned above puts the hint on the right side. i want my hint on the right, but i need a single horizontal line...
here's the sample layout that doesn't show the hint:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<EditText android:layout_width="fill_parent"
android:layout_gravity="center_vertical|right"
android:layout_height="wrap_content"
android:layout_margin="6dp"
android:textSize="16sp"
android:paddingRight="5dp"
android:id="#+id/c"
android:gravity="right"
android:hint="hello!!!"
android:scrollHorizontally="true"
android:maxLines="1"
android:singleLine="true"/>
</LinearLayout>
i checked on 1.6 and 2.1 emulators and it reproduces 100%, i'm prettysure it's a bug, i don't see the connection between single line and the hint.... what's more the hint got it's own layout in the TextView (mLayout and mHintLayout both exists, in onDraw if the text length is 0 mHintLayout if mHint is not null is used).
Did you try android:ellipsize="start"? This has worked great for me in the past when I've wanted my hint and EditText to be centered.
Looks like you're exactly right with the issue; I tried playing with your example layout and saw the same issue. I assume this is your bug report.
The easiest solution is to just change your layout, but that's probably not what you want to do. My first attempt at a work around would be to try not setting any of those three attributes in XML and then setting them in Java. If that doesn't work...
One option is to mimic the hint by either extending the EditText class and attempting to fix the code that lays out the hint yourself, or by overriding the onDraw method to create the hint, or perhaps by simply overlapping a regular TextView on top of the EditText, which you then show/hide manually. You could even have the view check if it's empty, and if so set the text to your hint text and change the color. When the view gains focus, check if its text is equal to your hint and, if so, remove the text and change the color back.
Another possible workaround that's a bit more "hacky" is to leave off the three attributes that cause problems, but try to manually prevent a newline from being created. You'd need to create an OnKeyListener for your EditText, something like this:
editText.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
// do nothing
return true;
}
return false;
}
});
You would also want to call editText.setImeOptions(EditorInfo.IME_ACTION_NEXT) to avoid showing the return key. It still may be possible to create a newline in your text field by pasting into it or perhaps some other method, so you would also want to parse and remove newlines when the form is submitted just to be safe. This is also not likely to do what you want as far as horizontal scrolling.
use these properties with hint and single line...u can chnge gravity!!
android:gravity="right"
android:ellipsize="start"
android:imeOptions="actionNext"
android:singleLine="true"
Noting worked good enough for me. When I set Gravity.right, the cursor was always on the right and couldn't be placed in the middle of the word.
I tried a different approach - put the set the gravity the the right when there is no text (or left, if it works for you) and let android decide the best direction once the user entered something
This worked for me:
create TextWatcher class
private static class FilterTextWatcher implements TextWatcher {
private WeakReference<Activity> mActivity;
public FilterTextWatcher(Activity activity) {
mActivity = new WeakReference<Activity>(activity);
}
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (mActivity.get() == null)
return;
EditText searchTxtBx = mActivity.get().mSearchTxtBx;
if (searchTxtBx.getText().toString().length() == 0)
searchTxtBx.setGravity(Gravity.RIGHT);
else
searchTxtBx.setGravity(0);
}
}
use it as class member
private TextWatcher mFilterTextWatcher = new FilterTextWatcher(this);
in onCreate():
mSearchTxtBx.addTextChangedListener(mFilterTextWatcher);
in onDestroy():
mSearchTxtBx.removeTextChangedListener(mFilterTextWatcher);
mFilterTextWatcher = null;
What do you think about my solution to this problem?
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus == false && StringUtils.isNotBlank(editText.getText().toString())) {
editText.setGravity(Gravity.RIGHT);
}
}
});
And the corresponding XML File:
<EditText android:id="#+id/the_text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="number" android:hint="#string/edit_text_prompt"/>
Works fine for me: just one line, no enter-key possible, shows me the hint and when I leave the field after some input was given, the text appears right-aligned.
it worked with me when I added:
android:hint="the hint text ..."
android:singleLine="true"
android:ellipsize="start"
and in my activity i added :
myedittext.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_ENTER&&event.getAction()==KeyEvent.ACTION_DOWN){
// do nothing
return true;
}
return false;
}
});
I noticed this issue when my TextView atrs are:
android:singleLine="true"
android:gravity="right"
When I try to Linkify the textview or setMovementMethod(LinkMovementMethod.getInstance()) on that textview, the text is just gone.
android:ellipsize="start"
solved my issue, because I use Arabic text in my app.