I want to append text to an android EditText view but I want that text to not be present in the popup editor. To be clear I want to put units in the EditText. So for example "10 gallons" but when the popup editor is displayed I only want to see and edit "10". Then when the value is returned I want the " gallons" appended back on to the view.
Is this possible in an automatic way or do I have to track onTouch() events and have a listener for the keyboard and manually append the units again?
I believe the onFocusChange method for EditText views would detect when a user is editing the text field. Try something like this..
EditText et = (EditText) findViewById(R.id.editText);
et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean b) {
if (b) {
((EditText)view).setText(String.valueOf(value));
} else {
value = Integer.valueOf(((EditText)view).getText().toString());
((EditText)view).setText(value + " gallons");
}
}
});
I am working on Android application in which I want to make my textfield editable and clickable. It has multiple TextFields and EditTexts on my screen. I have "EDIT" TextField for which I want to make it clickable and after clicking I want to make other field editable and enable. Without clicking edit Textfield all of them should not be enable.
My code snippet is given below:
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
fName = (TextView) findViewById(R.id.fnametxt);
lName = (TextView) findViewById(R.id.lastnameTxt);
mailText = (TextView) findViewById(R.id.mailTxt);
mobileText = (TextView) findViewById(R.id.mobileTxt);
dobText = (TextView) findViewById(R.id.dobTxt);
fName.setText(currentUserFirstName);
lName.setText(currentUserLastName);
dobText.setText("");
mobileText.setText(currentUserContactNumber);
mailText.setText(currentUserEmail);
}
You can't convert TextView to EditText, but you can rather use setEnabled property for EditText
You can use editText.setEnabled(true); to make the EditText editable.
Say you are having two edittexts as follows. And on entering data in first edittext, you need to make edittext2 editable, then you can do this:
EditText edittext1, edittext2;
//findViewByIds for both views
editText1.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if(s.length() != 0)
editText2.setEnabled(true);
else
editText2.setEnabled(false);
}
});
Hope this gives a clue how to use it.
EDIT:
Don't get confused between TextField, Button, EditText.
In Android, simple read only field is TextView. Editable textbox is called EditText, and Button is plain Button.
So as per what you are saying, you want tomake EditTexts editable upon clicking of a Button.
Use this:
EditText edittext1, edittext2;
Button button;
//findViewByIds for all views.
buton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
editText1.setEnabled(true);
editText2.setEnabled(true);
}
});
In my opinion, if you want to edit your textfield, then its better to go with EditText. The reason is as follows
The TextView's editable param does make it editable (with some restrictions).
If you set
android:editable="true"
you can access the TextView via the D-pad, or you could add
android:focusableInTouchMode="true"
to be able to gain focus on touch.
The problem is you cannot modify the existing text, and you cannot move the cursor. The text you write just gets added before the existing text.
Here is my scenario,
I just wanna get only number and a particular special character like $ at the end of the EditText field.
Ex: 234.34$
I don't wanna validate after entering this input, but rather user can only enter decimal number and at the end this special character.
Some one please help me to do this.
you can use the following (progromatically)
ed.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
ed.setKeyListener(DigitsKeyListener.getInstance("0123456789.$"));
you can define whatever characters you want within the DigitsKeyListener.getInstance
or if dont want the user to enter the $ sign and you want to be entered manually after the user finishes editting...
#Override
protected OnFocusChangeListener getOnFocusChangeListener() {
return new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
//Member variable in the class which contains an EditText
CurrencyTextbox.this.hadFocus = true;
} else {
// Thes EditText has lost focus
Log.v(TAG, "Lost focus.");
if (CurrencyTextbox.this.hadFocus) {
// We previously had focus, now we lost it, format the user input!
// Get current value of the Textbox
String value = CurrencyTextbox.this.textbox.getText().toString();
// Formatting the user input
value = String.format(//Doing some formatting);
// Reset the had focus
CurrencyTextbox.this.hadFocus = false;
}
}
}
};
Use this in your EditText android:inputType="numberDecimal"
In the Class file add a TextWatcher to the EditText as following code and in the method afterTextChanged(Editable s) add "$" at the end of the text in EditText.
EditText input = (EditText) findViewById(R.id.search_text_box);
input.addTextChangedListener(onInputTextChanged);
public TextWatcher onInputTextChanged = new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void afterTextChanged(Editable s)
{
// Add "$" at the end of text in EditText
}
};
In the Edit text add the property android:inputType="numberDecimal"
You can accept only numbers and phone number type using java code
EditText number1 = (EditText) layout.findViewById(R.id.edittext);
number1.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
number1.setKeyListener(DigitsKeyListener.getInstance("Replace with your special characters”));
This code will avoid lot of validations after reading input
I want to create EditTextFields dynamically on depending the condition. Condition is that if I start typing on first EditTextField it will create one more EditTextField in the bottom and will create the third EditTextField when i start typing on second one. Similarly i want to delete the bottom text if there is no text in the upper EditTextField. Thanks.
Use a parent view, like a ScrollView that you know you can add a flexible about of content to. Then use a TextWatcher a/k/a a text change listener. You could then create a new text view which you would add to the ScrollView if text was typed into the EditText field.
For neatness I'd probably create a custom TextView class that housed this text change listener and replication check. Here's example of how you could add a TextView
//instance variable
private LinearLayout containerLayout;
private newTextViewCreated = false;
//initialize your conatinerLayout before you use it
//and create your first edit text field
public void onCreate(Bundle savedInstaceState){
containerLayout = (LinearLayout)findViewById(R.id.conatinerLinearLayout);
createEditText();
}
private void createEditText(){
EditText editText = new editText(this);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(count > 0 && !newTextViewCreated){
createEditText();
newTextViewCreated = true;
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
//TODO Auto-generated method stub
}
});
containerLayout.addView(editText);
}
I didn't test this out, I'm writing it now but here's what I'm thinking. Read the description of how a TextWatcher works so you understand the inner methods. You're going to have to play with the conditionals but what you're doing is listening for a change in the number of characters entered and then making a recursive call to create an additional view when chars are added to each text view. I use a boolean flag to show when a view has been created so we don't add one each time the char is changed. I moved outside the createEditText method based on your comment. If you made your own EditText class you could just add a method that would set/get the status of whether this TextView had spanwed another. To remove you would just add a delete condition that would remove the view from the linear layout.
User TextWatcher
Implement your Activity with TextWatcher and override method
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
Show / Hide them in your layout if you know the total amount of editText fields needed or add them programatically like so:
EditText myET = new EditText(MyActivity.this);
myET.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
LayoutContentView.addView(myET);
Then check:
if (myET.getText().toString().trim().equals(""))
{
//Don't Show
}else{
//SHOW
}
SO question could help:https://stackoverflow.com/a/6792359/350421
EditText toAdd = new EditText(this);
list.add(toAdd);
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);