0

I have one EditText defined in xml and I want to add another one dynamically but when the app runs, the dynamically added behaves like TextView. I can't type in any text and no caret shows. It doesn't even look like EditText that I include statically. See the image.

enter image description here

I have latest Android Studio, latest emulators, tried it on API 28 and also on physical device Samsung S8+ API 26 and it works same weird way everywhere. And worst is that I'm sure in the past it worked.

Any idea please how I could find out what's wrong? Fix it?

Code:

public class TActivity extends AppCompatActivity {

 private LinearLayout Layout;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.t);

  Layout = (LinearLayout) findViewById(R.id.Layout);

  EditText Textbox = new EditText(this);
  Textbox.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
  Textbox.setText("My text");
  //Textbox.setEnabled(true);
  Layout.addView(Textbox);
 }
}

Layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/Layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/ThisWorks"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"/>
</LinearLayout>
Pratik Butani
  • 60,504
  • 58
  • 273
  • 437

1 Answers1

3

Instead of setting text try setting hint and setEnabled true

   EditText editText = new EditText(this);
      editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
      editText.setHint("My Text");
      editText.setEnabled(true);
      //editText.setEditable(true);
      Layout.addView(editText);
Surbhi Aggarwal
  • 777
  • 8
  • 25
  • Thanks but it doesn't work. How did you build it. setEditable doesn't even exist in API 28. –  Mar 12 '19 at 15:58
  • Let's say, i removed the line `setEditable` even then if you use setEnabled true and it will work. I used the same code as yours and used the EditText code with setEditable line commented and it worked fine. Just use `setEnabled` as `true` – Surbhi Aggarwal Mar 12 '19 at 17:03
  • Of course, I removed setEditable but it didn't work. Then I wrote my first comment. However, as I see if it works for you the issue will be in the styles applied to the activity. However, I need to prove it. The styles are Android ones ... . Thanks anyway –  Mar 12 '19 at 17:08
  • O.K., so it works. It seemed it didn't work because Android applies different theme to dynamic elements (dynamic EditText has no border, etc.) but for that one I ask other question. Thank you –  Mar 12 '19 at 18:33