How to make a TextView editable at the click of a button?

16.7k views Asked by At

I have an app that displays certain content from a database and lets users edit it. I have an activity that displays those details in some textviews. Now, there is an "EDIT" button at the bottom of the screen. When this button is clicked, I want to make the textview's editable (which are initially read-only) so that the database can be updated. Also, I want the "EDIT" button to turn into a "SAVE" button. I understand I can just use another activity for this, but is there any way to do this while in the same activity?

3

There are 3 answers

3
Elltz On BEST ANSWER

EditText is a TextView, what it can do TextView can do better

so suppose you have a TextView

 <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"        
    android:text="i am a text"
    android:textColor="#243b03" />

and you want it to be editable by a click of a button; in your onclick add this

   TextView.setCursorVisible(true);
   TextView.setFocusableInTouchMode(true);
   TextView.setInputType(InputType.TYPE_CLASS_TEXT);
   TextView.requestFocus(); //to trigger the soft input

they are not static, but i made it static so you know which view object's methods are those. About your Button after the text has been inputted then you change the text to "done" or whatever, Button extends from TextView so treat it as if it was-research on TextWatcher

1
Galax On

You'd be better off to switch the TextView to an EditText and toggle it with editText.setEnabled(boolean) to get the effect you want

0
Tim John On

Making a textview editable has its limitations, such as not being able to modify the data already in it (Check this answer)

You can just use an EditText and use android:inputType="none" in xml or use <your_editText>.setEnabled(false) in your activity/fragment to make it read-only. After the user clicks EDIT, you can make the editText editable by putting the below statements inside the button's onClick method.

<your_editText>.setEnabled(true) <your_editText>.requestFocus();

Regarding making the EDIT button turn into SAVE, you can put a counter inside your onClick method which will keep track of the order of clicks. After the first click you can change the button text using

<your_button>.setText("SAVE").

On the next click you can execute whatever statements you're using to save data.