[Solved] Android: Error with adding textview to linearlayout


1. First create a file ids.xml in your /res directory and add the following XML schema to this file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item type = "id" name = "mytextbox"></item>
</resources>

2. Your onCreate() method should look like this:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_selection_screen);

    if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }
}

3. Add the following code to your PlaceholderFragment:

@Override
public void onViewCreated(final View view, Bundle savedInstanceState){

    LinearLayout l = (LinearLayout) view.findViewById(R.id.scrolllayout);
    EditText e = new EditText(view.getContext());
    e.setId(R.id.mytextbox);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
    e.setLayoutParams(lp);
    l.addView(e);

}

Try this. It will work.

NOTE: I can see that you attempted to add the EditText from your Activity, and maybe you don’t want to do it from your Fragment. If you would still prefer to do it from your Activity, let me know. There are ways to do it, but when dealing with a Fragment it is always safer to add/remove views after the Fragment has been successfully created.

2

solved Android: Error with adding textview to linearlayout