-2

so I know the onClick part is quite useless, but just in case it does change anything, ive put it there. so ive got the onClick, and I would like it to add the editText to the current activity, which is called activity_calculation. I currently have this code which I got from another question :

public void addCalc(View view){

EditText myEditText = new EditText(context); // Pass it an Activity or Context
        myEditText.setLayoutParams(new LinearLayoutCompat.LayoutParams(MATCH_PARENT,WRAP_CONTENT)); // Pass two args; must be LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, or an integer pixel value.
        activity_calculation.addView(myEditText);

    }

any help would be appreciated. maybe you can see what ive done wrong

Prokash Sarkar
  • 11,723
  • 1
  • 37
  • 50
  • Why you are creating in onClick.... You Hide the edit text and change visibility during onClick Also... Which might be easy.... You Can Consider That too... If possible – Mukeshkumar S Nov 22 '16 at 11:11
  • 1
    @MaharithAdityaSS I use onClick because I need the user to add edit texts as much as he needs, its not a set amount, where I can change the visibility, if u understand what I mean...? – Muaaz Kasker Nov 22 '16 at 13:48
  • Possible duplicate of [Android adding textview programatically](http://stackoverflow.com/questions/16730618/android-adding-textview-programatically) – AxelH Nov 22 '16 at 14:21

1 Answers1

2

First get a reference to the activity's root layout. To do this add an id attribute to your activity layout file's root layout. eg :

<LinearLayout
    android:id="+id/rootLayout" />

Then, get a reference to it and add the created EditText.

//If your root layout is a RelativeLayout, use that instead
LinearLayout rootView = (LinearLayout) findViewById(R.id.rootLayout);
EditText myEditText = new EditText(rootView.getContext()); 
myEditText.setLayoutParams(new LinearLayoutCompat.LayoutParams(MATCH_PARENT,WRAP_CONTENT)); 
rootView.addView(myEditText);
rhari
  • 1,367
  • 1
  • 11
  • 19