How to set text of a TextView using EditText? [duplicate] - android

This question already has an answer here:
automatically update my activity to show which was written
(1 answer)
Closed 8 years ago.
Using a text field, how would I set the text of a TextView while constantly updating the text? For example: The user begins to type information into the text field, this changes some text in in the activity they're in, however, the user does not need to manually update the text, instead the text automatically refreshes.
I have tried doing this myself and searched for other dilemmas, yet nothing appears to work. Additionally, I'm working with fragments that could possibly cause the problem. The code is below, partitioned into areas, before onCreateView(), in onCreateView() and after onCreateView().
Before onCreateView():
// Edit Text
EditText exerciseOneTitle;
// String value, contains value of exerciseOneTitle
String value;
// titleOne, what I want to the user to be able to change
TextView titleOne;
During onCreateView():
// Edit text
exerciseOneTitle = (EditText) rootView.findViewById(R.id.exercise_text);
// Get Edit Text value
value = exerciseOneTitle.getText().toString();
// Set title so there is always an initial value
titleOne.setText(R.string.exercise_one);
// Checks if edit text is focused
exerciseOneTitle.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
// While edit text is focused, update titleOne via refresh()
while (hasFocus == true) {
refresh();
}
}
});
After onCreateView():
// Get the updated "value" and set it as titleOne text
// Additionaly, will be using it in other situations
public void refresh() {
value = exerciseOneTitle.getText().toString();
titleOne.setText(value);
}
Any thoughts or ideas? Thanks!

You can use TextWatcher.. See the link
According to the docs
onTextChanged() is called to notify you that, within s, the count
characters beginning at start have just replaced old text that had
length before. It is an error to attempt to make changes to s from
this callback.
Try this..
tv = (TextView)findViewById(R.id.charCounts);
textMessage = (EditText)findViewById(R.id.textMessage);
textMessage.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
tv.setText(textMessage.getText().toString());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});

Related

Failing to get the value of an EditText in ViewHolder of RecyclerView

In my app, I have a RecyclerView with editable EditText views as part of the ViewHolder, see picture:
The user can edit the values of the EditText views. To save the changed value back to the related adapter, set an OnFocusChangeListener to the EditText views, storing the (changed) value as soon as they loose focus, see following code snippet, taken from the onBindViewHolder method of my adapter:
// Add listener to views
holder.fpuView.setOnFocusChangeListener((v, hasFocus) -> {
if (!hasFocus) {
// Focus has gone, so save value to adapter
mAbsorptionBlocks.get(position).setMaxFPU(Integer.valueOf(holder.fpuView.getText().toString()));
}
});
holder.absorptionTimeView.setOnFocusChangeListener((v, hasFocus) -> {
if (!hasFocus) {
// Focus has gone, so save value to adapter
mAbsorptionBlocks.get(position).setAbsorptionTime(Integer.valueOf(holder.absorptionTimeView.getText().toString()));
}
});
This works fine, as long as the user taps another EditText view.
It does NOT work if the user directly hits the "Save" button immediately after having changed the value of the EditText. The EditText seems not recognize that is has lost focus. This is probably due to the Save button does not belong to the RecyclerView, but to the parent activity.
I played around with other listener options, but I'm pretty lost now. Is there any chance to grasp the changed values when the user hits the Save button directly after editing the value?
You must these method of EditText
holder.fpuView.addTextChangedListener(new
TextWatcher() {
#Override
public void afterTextChanged(Editable s) {}
#Override
public void beforeTextChanged(CharSequence s, int
start,int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if(s.length() != 0) {
mAbsorptionBlocks.get(position). setMaxFPU(Integer.valueOf(holder.fpuView.getText().toString()));
}else{
// add default value when EditText is empty.
}
}
});
Use OnTestChangeListener instead. Then catch the after text changed event or in real time if you prefer. That way you aren't relying on the focus change event to get the text.

Text watcher in edit text is making the edittext slow

In my tablet app I have used fragments and one fragment has multiple Edittexts, and I have a linear layout which will add a sublayout as many times the user wishes to add, in that fragment
This sublayout has two edittext, both this edittext is having
addtextchangelistener(Textwatcher) and
onfocuschangelistner
every time the text is changed 3 conditions are checked in both the edittext
every time the focus is changed 2 conditions are checked in both the edittext
After doing all this condition check, the problem I'm facing is, the edittext typing is too slow, its like i type an email and the whole email gets completely typed after 5 secs or more,
This is the code for 1 edit text in the sublayout:
receiverName.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View paramView, boolean hasFocus) {
receivernameFocus = hasFocus;
if(hasFocus)
{
if(receiverName.getText().toString().length()>0)
ReceiverName_btn_cancel.setVisibility(View.VISIBLE);
else
ReceiverName_btn_cancel.setVisibility(View.INVISIBLE);
}
else
ReceiverName_btn_cancel.setVisibility(View.INVISIBLE);
}
});
receiverName.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence paramCharSequence, int paramInt1,int paramInt2, int paramInt3) {
if(receivernameFocus)
{
if(receiverName.getText().toString().length()>0)
{
receiverNamePresent = true;
ReceiverName_btn_cancel.setVisibility(View.VISIBLE);
}
else
{
receiverNamePresent = false;
ReceiverName_btn_cancel.setVisibility(View.INVISIBLE);
}
}
else
ReceiverName_btn_cancel.setVisibility(View.INVISIBLE);
if(receiverEmailPresent && receiverNamePresent)
addReceiver.setBackgroundResource(R.drawable.plus_receiver);
else
addReceiver.setBackgroundResource(R.drawable.plus_deselect_receiver);
}
#Override
public void beforeTextChanged(CharSequence paramCharSequence,
int paramInt1, int paramInt2, int paramInt3) {
}
#Override
public void afterTextChanged(Editable paramEditable) {
}
});
same conditions are present for the other edittext, and everytime the user inflate another view, same set of edittext will be created for the new view too.
I can't remove the conditions, all of them are necessary, and you can see its just some button visibility or setting background resource
How to optimize this code, or how to speed up the edittext typing speed for android tablet?
EDIT: If I'm typing 10 letters persecond its showing only 1 letter per second in the edittext(so all the 10 letters will be visible in the edittext after 10 seconds), which I believe is happening because of multiple condition checking within onTextChanged method, the delay in showing the text is too much for user experience.
How to make the edittext show the text as fast as I'm typing it
Thanks
Here public void onTextChanged(CharSequence paramCharSequence, int paramInt1,int paramInt2, int paramInt3) it's generally in this format:
public void onTextChanged(CharSequence s, int start, int before, int count)
So here you will need to do some operation using paramInt3 . If you would like to show suggest text will come after you enter 3 letter then perform an operation here in this manner:
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (count%3 == 1)
{
adapter.clear();
GetPlaces task = new GetPlaces();
task.execute(dep_place.getText().toString());
}
}
here I haved updated text from server side in background. You just need to modify this portion from where your text will come use this code here.
Thanks.

Adding EditText fields on view when typing on a EditText

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

Associate EditText with a TextView for labeling purposes

Hi I am learning Android programming and have run into an issue that I couldn't get a clear answer to through researching.
I have a TextView which serves as a label for my EditText. I have a method which checks if the EditText is an empty String. If the string is empty I want to be able to get a reference to the TextView that corresponds to that EditText in order to make a toast saying something like "please enter a value for ".
I've looked into getLabelFor/setLabelFor but is there a way to do this in the layout XML?
What is best practice for this type of functionality.
You're describing a functionally that is build in to EditText. There is a special field you can define in xml called hint, which is the recommended way to label an EditText rather than a nearby TextView. Additionally, EditText has a method called setError() (link). If the user attempts to hit a submit button, for example, you can check to see if the EditText is empty and if so, call setError().
I wonder if the following is the thing that you need
TextWatcher inputTextWatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after){
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().equals("")) {
textView.setText("please enter a value for ..");
} else {
textView.setText("<the textedit is not empty>");
}
}
public void afterTextChanged(Editable s) {
}
};
editText.addTextChangedListener(inputTextWatcher);

Check if an EditText was modified

My app should open a file inside an edittext to show it to the user. If user want to modify it just press inside textwiew and write it. After do this when back button is pushed, if the text was modify, the changes should be saved, else, just close the current activity and go to parent.
There's a way to see if the text was edited?
My idea is to explicitly compare file and edittext character length, but there's something better than this "rude" method?
You can use a TextWatcher:
boolean changed = false;
EditText edit = (EditText)findViewById(R.id.medittext);
edit.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
changed = true;
}
});
Just comparing the length might result in a false negative if the changes are of the same length as deletions in the text.
When the user presses back, just check if changed is true. This might result in a false positive if the user made an edit and then undid it, but it is better to have a few false positives than to lose user changes.
Nothing better actually you have to compare the text and not the length. The user could just replace a word. A TextWatcher would tell you that a user is editing but he just may change and change it back. So you really need to compare strings.

Categories

Resources