Make EditText behave as a TextView in code

后端 未结 8 2406
暗喜
暗喜 2020-12-29 13:39

How to make an EditText look like a TextView that is done in Java but not in XML..

I have seen how to do it using xml file like

style=\"@android:styl         


        
8条回答
  •  梦谈多话
    2020-12-29 14:13

    Well I know this was a very old question, but I have to do this one of my apps and came up with a simple approach deduced from all the answers from Google/stack overflow. Suppose u want to make a edit text look like a text view and on button click make it editable, the procedure is as follows:

    In your layout, set:

     
    

    And in your .java set the color of the text by:

    yourEditText.setTextColor(Color.parseColor("#000000"));
    

    before entering the onClick of button. And in the onClick of button:

    InputMethodManager imm = (InputMethodManager)               getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(postContent, InputMethodManager.SHOW_IMPLICIT);//shows   keyboard
    int position = postContent.length();
    Editable text = postContent.getText();
    yourEditText.setBackground(getResources().getDrawable(R.drawable.border));//shows a border around your text view making it look like a edit text
    yourEditTex.setEnabled(true);//enables the edit text which we disabled in layout file
    yourEditTex.setCursorVisible(true);
    Selection.setSelection(text,position-1);`//places the cursor at the end of the text
    

    Now to make the edit text show again as a textView, on the onClick of another button:

    String s = postContent.getText().toString();
    yourEditText.setText(s);
    yourEditText.setEnabled(false);
    yourEditText.setTextColor(Color.parseColor("#000000"));
    yourEditText.setBackground(null);`
    

    My answer covers two or three questions combined, but I hope it'll be helpful.

提交回复
热议问题