hint and textview with right gravity and a singleline - android

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.

Related

Setting EditText imeOptions to actionNext has no effect when using digits

Here my edittext:-
<com.os.fastlap.util.customclass.EditTextPlayRegular
android:id="#+id/full_name_et"
style="#style/Edittext_white_13sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/_5sdp"
android:background="#00ffffff"
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
android:imeOptions="actionNext"
android:inputType="text"
android:maxLength="20"
android:maxLines="1"
android:nextFocusDown="#+id/last_name_et"
android:textCursorDrawable="#null" />
When I remove digit in edittext it work fine but with digit imeOptions doesn't work. But one surprising thing if I use singleLine instead of maxLines it work fine. But singleLine now is deprecated. I cannot remove digit in my edittext and I don't want use deprecated method. Any one can solve this problem. Thanks in adavance
Here is a simplified solution with the software keyboard button "Next":
final String NOT_ALLOWED_CHARS = "[^a-zA-Z0-9]+";
final EditText editText = (EditText) findViewById(R.id.editText);
editText.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) {
if (!TextUtils.isEmpty(s)) {
// remove the listener to avoid StackoverflowException
editText.removeTextChangedListener(this);
// replace not allowed characters with empty strings
editText.setText(s.toString().replaceAll(NOT_ALLOWED_CHARS, ""));
// setting selection moves the cursor at the end of string
editText.setSelection(editText.getText().length());
// add the listener to keep watching
editText.addTextChangedListener(this);
}
}
});
Here the regular expression [^a-zA-Z0-9]+ corresponds to the allowed values of android:digits of the EditText in question.
you can use
android:lines="1"
in place of
android:maxLines
or
android:singleLine="true".
I know you have tried many solutions, Try with
android:lines="1"
these if you haven't tried earlier.
The problem is you are clicking on Enter key instead of the actionNext you need in order to move cursor to next EditText
Specify the Input Method Action
Most soft input methods provide a user action button in the bottom
corner that's appropriate for the current text field. By default, the
system uses this button for either a Next or Done action unless your
text field allows multi-line text (such as with
android:inputType="textMultiLine"), in which case the action button is
a carriage return. However, you can specify additional actions that
might be more appropriate for your text field, such as Send or Go.
It causes carriage return for your action button. So it means that doesn't fire android:nextFocusDown
First of all, lets see what is difference between singleLine which is deprecated and maxLines
singleLine
When you set android:singleLine="true" one line text is in EditText visible but Enter key isn't visible in keypad
maxLines
when you set android:maxLines attribute with the particular value only same amount of line text is visible in EditText and enter key in keypad also visible for Entering.
So When you click action button it is firing Enter Action according to your code. Also you must change your inputType attribute with android:inputType="textMultiLine" if you use android:maxLines attribute
maxLines
added in API level 1 int maxLines Makes the TextView be at most this
many lines tall. When used on an editable text, the inputType
attribute's value must be combined with the textMultiLine flag for the
maxLines attribute to apply.
May be an integer value, such as "100".
When I customized your code with the correct attributes still it was firing Enter key instead of IME_ACTION_NEXT which you want. I think it didn't solve the problem due to
textMultiLine Can be combined with text and its variations to allow
multiple lines of text in the field. If this flag is not set, the text
field will be constrained to a single line. Corresponds to
TYPE_TEXT_FLAG_MULTI_LINE.
TYPE_TEXT_FLAG_MULTI_LINE
added in API level 3 int TYPE_TEXT_FLAG_MULTI_LINE Flag for
TYPE_CLASS_TEXT: multiple lines of text can be entered into the field.
If this flag is not set, the text field will be constrained to a
single line. The IME may also choose not to display an enter key when
this flag is not set, as there should be no need to create new lines.
Constant Value: 131072 (0x00020000)
SOLUTION:
Subclass EditText and adjust the IME options. After that you don't need android:maxLines or android:singleLine attributes.
#Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
InputConnection connection = super.onCreateInputConnection(outAttrs);
int imeActions = outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION;
if ((imeActions&EditorInfo.IME_ACTION_NEXT) != 0) {
// clear the existing action
outAttrs.imeOptions ^= imeActions;
// set the DONE action
outAttrs.imeOptions |= EditorInfo.IME_ACTION_NEXT;
}
if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) {
outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
}
return connection;
}
You could also check another post here. I reconfigured the accepted answer of this post on your purpose
android:digits specifies that the EditText has a numeric input method, as per the docs
You could use android:inputType="personName" to achieve the same as your current digits attr
android:maxLines only Makes the TextView be at most this many lines tall, not prevent user from input more characters.
The same with android:lines that only makes the TextView be exactly this many lines tall.
The workaround code for your solution are as below,
XML File
<EditText
android:id="#+id/full_name_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5sp"
android:background="#00ffffff"
android:imeOptions="actionNext"
android:inputType="text"
android:maxLines="1"
android:maxLength="20"
android:textCursorDrawable="#null" />
Java:
final EditText edtfirstName = (EditText) findViewById(R.id.full_name_et);
edtfirstName.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
if (charSequence.toString().startsWith(" ")) {
String result = charSequence.toString().replace(" ", "").replaceAll("[^a-zA-Z]+", "");
if (!charSequence.toString().equals(result)) {
edtfirstName.setText(result);
edtfirstName.setSelection(result.length());
}
} else {
String result = charSequence.toString().replaceAll("[^a-zA-Z ]+", "");
if (!charSequence.toString().equals(result)) {
edtfirstName.setText(result);
edtfirstName.setSelection(result.length());
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
});

error message displaying continuously in TextInputLayout

This code is in a layout file.
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textInputLayoutMobile"
>
<EditText
android:inputType="number"
android:id="#+id/mobileNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLength="10"
android:hint="Mobile Number" />
</android.support.design.widget.TextInputLayout>
This is Java code.
TextInputLayout textInputLayoutMobile = (TextInputLayout)findViewById(R.id.textInputLayoutMobile);
textInputLayoutMobile.setErrorEnabled(true);
textInputLayoutMobile.setError("This field is required");
Current behaviour: When we click on the field, it shows, "This field is required". Also when we start typing in the field, this message does not go away.
Desired behaviour: When we click for the first time, it should not show, "This field is required". When we move to another field after touching this field and without entering any data, it should show, "This field is required". Also when we start typing in the field, this message should go away.
I think you must use text change listener
edit.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) {
//set error
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
and on his method to set your desire output.. hope to help you!
I believe the error is that those two lines of code are used while retrieving the textInputLayoutMobile from your layout (probably in onCreate). So the view is set to always display this error message.
textInputLayoutMobile.setErrorEnabled(true);
textInputLayoutMobile.setError("This field is required");
I suppose those two lines should be moved from this point and set there where you should validate the textInputLayoutMobile input and deciding that the validation is wrong, e.g. in an onClick callback or listener. Additionally when your input is validated to true then set textInputLayoutMobile.setErrorEnabled(false);
See an example here: http://code.tutsplus.com/tutorials/creating-a-login-screen-using-textinputlayout--cms-24168
I think you need take id="#+id/mobileNumber", set the widget and than try something like that
your_widget.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
if (yourwidget.getText().toString().length() == 0) {
yourwidget.setError("This field is required");}
else etc...
You could use this control on a "next" button or something like that (save button etc) insted of use that on the field directly (sorry for my english)
I think you need to take the reference of EditText and not the TextInputLayout.
Try
EditText editText = (EditText)findViewById(R.id.mobileNumber);
editText.setError("This field is required");

EditText - have default text that cannot be deleted, and cover text with background after leaving EditText

I am creating an email form and would like to have text in an EditText that cannot be deleted. On the screenshot below, the To could not be deleted.
If anyone has suggestions on how to achieve the above, it would be great - Thanks.
My current code for the To EditText box:
<EditText
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="0dp"
android:hint="#string/email_to" >
</EditText>
The problem is android:hint text dissappears when the user starts to text, and android:text can be deleted by the user.
How do we have text that cannot be deleted? Thanks.
Note:
Also, I would like to note that I have a method that clears text using a clear button - this works fine - but I am hoping that it would not delete the fixed text (If I got that implemented!).. Here`s the code for that:
private void clearForm(ViewGroup group)
{
for (int i = 0, count = group.getChildCount(); i < count; ++i) {
View view = group.getChildAt(i);
if (view instanceof EditText) {
((EditText)view).setText("");
}
if(view instanceof ViewGroup && (((ViewGroup)view).getChildCount() > 0))
clearForm((ViewGroup)view);
}
}
SOLUTION:
Managed a roundabout way of doing this.. I created a TextView and EditText within a nested Linear Layout. I turned off the border in the EditText using android:background="#00000000".
I created an xml file in the drawable folder, and refered to this in the relevant linear layout like this: android:background="#drawable/customxml"
You can do it by using Text Watcher listener.
You can keep text in edittext by checking length of edittext.
For example
editText.setText("To") // it mean have lenght 2
And Than in method afterTextChanged, check if text in editText is has been deleted (with check length of text in editText)
This is for complete example code:
editText.setText("To");
editText.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) {
if(s.length < 2){
editText.setText("To")//set editext with "To" again like has been initialized
editText.setSelection(editText.getText().length)// to make cursor in end of text
}
}
});
Hope this help!
To get the visual appearance you want, include a horizontal LinearLayout containing a text view and an EditView. Turn off the border around the EditView (there's an attribute that does that (I think it's android:shadowColor) ) Play around with margins and padding to get them to be adjacent to each other. Set the background color on the linear layout to put a border around the combined pair.
I wouldn't worry much about efficiency. You aren't nesting very deeply. The biggest challenge is going to be getting it to look like a single view.
Edit: Another thought. If that doesn't work, you could make the "To" a drawable, and set it using the android:drawableLeft attribute.
Add TextView to the right side of EditText in LinearLayout with horizontal orientation or RelativeLayout with android:layout_toRightOf="#id/YourTextView"

Disable input method of EditText but keep cursor blinking

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);
}

Make EditText ReadOnly

I want to make a read-only EditText view. The XML to do this code seems to be android:editable="false", but I want to do this in code.
How can I do this?
Please use this code..
Edittext.setEnabled(false);
If you setEnabled(false) then your editText would look disabled (gray, etc). You may not want to change the visual aspect of your editor.
A less intrusive way would be to use setFocusable(false).
I believe that this answers your question closer to your initial intent.
In XML use:
android:editable="false"
As an example:
<EditText
android:id="#+id/EditText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:editable="false" />
This works for me:
EditText.setKeyListener(null);
editText.setInputType(InputType.TYPE_NULL);
As per the docs this prevents the soft keyboard from being displayed. It also prevents pasting, allows scrolling and doesn't alter the visual aspect of the view. However, this also prevents selecting and copying of the text within the view.
From my tests setting setInputType to TYPE_NULL seems to be functionally equivalent to the depreciated android:editable="false". Additionally, android:inputType="none" seems to have no noticeable effect.
android:editable="false" has been deprecated. Therefore you cant use it to make the edit text readonly.
I have done this using the bellow solution. Here I have used
android:inputType="none"
android:textIsSelectable="true"
android:focusable="false"
Give it try :)
<EditText
android:id="#+id/et_newsgpa_university"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="#string/hint_educational_institute"
android:textSize="#dimen/regular_text"
android:inputType="none"
android:textIsSelectable="true"
android:focusable="false"
android:maxLines="1"
android:imeOptions="actionNext"/>
The best is by using TextView instead.
editText.setEnabled(false);
editText.setFilters(new InputFilter[] { new InputFilter() {
public CharSequence filter(CharSequence src, int start, int end,
Spanned dst, int dstart, int dend) {
return src.length() < 1 ? dst.subSequence(dstart, dend) : "";
}
} });
This will give you uneditable EditText filter. you first need to put the text you want on the editText field and then apply this filter.
writing this two line is more than enough for your work.
yourEditText.setKeyListener(null);
yourEditText.setEnabled(false);
set in XML
android:inputType="none"
Try using
editText.setEnabled(false);
editText.setClickable(false);
Try overriding the onLongClick listener of the edit text to remove context menu:
EditText myTextField = (EditText)findViewById(R.id.my_edit_text_id);
myTextField.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return true;
}
});
android:editable
If set, specifies that this TextView has an input method. It will be a textual one unless it has otherwise been specified. For TextView, this is false by default. For EditText, it is true by default.
Must be a boolean value, either true or false.
This may also be a reference to a resource (in the form #[package:]type:name) or theme attribute (in the form ?[package:][type:]name) containing a value of this type.
This corresponds to the global attribute resource symbol editable.
Related Methods
If you just want to be able to copy text from the control but not be able to edit it you might want to use a TextView instead and set text is selectable.
code:
myTextView.setTextIsSelectable(true);
myTextView.setFocusable(true);
myTextView.setFocusableInTouchMode(true);
// myTextView.setSelectAllOnFocus(true);
xml:
<TextView
android:textIsSelectable="true"
android:focusable="true"
android:focusableInTouchMode="true"
...
/>
<!--android:selectAllOnFocus="true"-->
The documentation of setTextIsSelectable says:
When you call this method to set the value of textIsSelectable, it sets the flags focusable, focusableInTouchMode, clickable, and longClickable to the same value...
However I had to explicitly set focusable and focusableInTouchMode to true to make it work with touch input.
Use this code:
editText.setEnabled(false);
editText.setTextColor(ContextCompat.getColor(context, R.color.black);
Disabling editText gives a read-only look and behavior but also changes the text-color to gray so setting its text color is needed.
this is my implementation (a little long, but useful to me!):
With this code you can make EditView Read-only or Normal. even in read-only state, the text can be copied by user. you can change the backgroud to make it look different from a normal EditText.
public static TextWatcher setReadOnly(final EditText edt, final boolean readOnlyState, TextWatcher remove) {
edt.setCursorVisible(!readOnlyState);
TextWatcher tw = null;
final String text = edt.getText().toString();
if (readOnlyState) {
tw = new TextWatcher();
#Override
public void afterTextChanged(Editable s) {
}
#Override
//saving the text before change
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
// and replace it with content if it is about to change
public void onTextChanged(CharSequence s, int start,int before, int count) {
edt.removeTextChangedListener(this);
edt.setText(text);
edt.addTextChangedListener(this);
}
};
edt.addTextChangedListener(tw);
return tw;
} else {
edt.removeTextChangedListener(remove);
return remove;
}
}
the benefit of this code is that, the EditText is displayed as normal EditText but the content is not changeable. The return value should be kept as a variable to one be able revert back from read-only state to normal.
to make an EditText read-only, just put it as:
TextWatcher tw = setReadOnly(editText, true, null);
and to make it normal use tw from previous statement:
setReadOnly(editText, false, tw);
This worked for me, taking several of the suggestions above into account. Makes the TextEdit focusable, but if user clicks or focuses, we show a list of selections in a PopupWindow. (We are replacing the wacky Spinner widget). TextEdit xml is very generic...
public void onCreate(Bundle savedInstanceState) {
....
fEditState = (EditText) findViewById(R.id.state_edit);
fEditState.setLongClickable(false);
fEditState.setKeyListener(null);
fEditState.setFocusable(true);
fEditState.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus)
{
if (hasFocus)
{
showStatesPopup();
}
}
});
fEditState.setOnClickListener(new Button.OnClickListener(){
public void onClick(View arg0)
{
showStatesPopup();
}
});
....
}
private void showStatesPopup()
{
// fPopupWindowStates instantiated in OnCreate()
if (!fPopupWindowStates.isShowing()) {
// show the list view as dropdown
fPopupWindowStates.showAsDropDown(fEditState, -5, 0);
}
}
This was the only full simple solution for me.
editText.setEnabled(false); // Prevents data entry
editText.setFocusable(false); // Prevents being able to tab to it from keyboard
As android:editable="" is deprecated,
Setting
android:clickable="false"
android:focusable="false"
android:inputType="none"
android:cursorVisible="false"
will make it "read-only". However, users will still be able to paste into the field or perform any other long click actions. To disable this, simply override onLongClickListener().
In Kotlin:
myEditText.setOnLongClickListener { true }
suffices.
My approach to this has been creating a custom TextWatcher class as follows:
class ReadOnlyTextWatcher implements TextWatcher {
private final EditText textEdit;
private String originalText;
private boolean mustUndo = true;
public ReadOnlyTextWatcher(EditText textEdit) {
this.textEdit = textEdit;
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (mustUndo) {
originalText = charSequence.toString();
}
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
if (mustUndo) {
mustUndo = false;
textEdit.setText(originalText);
} else {
mustUndo = true;
}
}
}
Then you just add that watcher to any field you want to be read only despite being enabled:
editText.addTextChangedListener(new ReadOnlyTextWatcher(editText));
I had no problem making EditTextPreference read-only, by using:
editTextPref.setSelectable(false);
This works well when coupled with using the 'summary' field to display read-only fields (useful for displaying account info, for example). Updating the summary fields dynamically snatched from http://gmariotti.blogspot.com/2013/01/preferenceactivity-preferencefragment.html
private static final List<String> keyList;
static {
keyList = new ArrayList<String>();
keyList.add("field1");
keyList.add("field2");
keyList.add("field3");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
for(int i=0;i<getPreferenceScreen().getPreferenceCount();i++){
initSummary(getPreferenceScreen().getPreference(i));
}
}
private void initSummary(Preference p) {
if (p instanceof PreferenceCategory) {
PreferenceCategory pCat = (PreferenceCategory) p;
for (int i = 0; i < pCat.getPreferenceCount(); i++) {
initSummary(pCat.getPreference(i));
}
} else {
updatePrefSummary(p);
}
}
private void updatePrefSummary(Preference p) {
if (p instanceof ListPreference) {
ListPreference listPref = (ListPreference) p;
p.setSummary(listPref.getEntry());
}
if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
//editTextPref.setEnabled(false); // this can be used to 'gray out' as well
editTextPref.setSelectable(false);
if (keyList.contains(p.getKey())) {
p.setSummary(editTextPref.getText());
}
}
}
Set this in EdiTextView xml file
android:focusable="false"
in java file:
Edittext.setEnabled(false);
in xml file:
android:editable="false"
These 2 lines makes ur edittext selectable and at the same time not editable (it doesn't even show the soft keyboard):
editText.setInputType(InputType.TYPE_NULL);
editText.setTextIsSelectable(true);

Categories

Resources