1

I'm trying to make a TextView programmatically in a LinearLayout. The program includes a checking system to check if its been added already and the prompt for creating the textview is an option in a spinner. Here is the full onClick method for the spinner

public void onClick(String Ingredient, int i) {

            Toast.makeText(Kitchen.super.getContext(), "Selected "+Ingredient, Toast.LENGTH_SHORT).show();

            if(Ingredient.equals(tomatoSauce.name)) {

                if (tomatoSauce.init == 0){

                    tomatoSauce.init = 1;
                    TextView one = new TextView(getContext());
                    one.setText(Ingredient);
                    mainll.addView(one);

                }


            } else if(Ingredient.equals(chicken.name)) {

                chicken.init = 1;

            } else if(Ingredient.equals(olives.name)){

                olives.init  = 1;

            }

        }

The Linear layout is identified from the xml layout when the app is started in a separate method.

final LinearLayout mainll = (LinearLayout) getActivity().findViewById(R.id.main);

The app crashes upon selecting Tomato Sauce from the menu despite the lack of identified coding errors. Any help with this issue would be greatly appreciated.

Keith
  • 39
  • 1
  • 8
  • refer https://stackoverflow.com/questions/3204852/android-add-a-textview-to-linear-layout-programmatically – sasikumar Jul 19 '17 at 16:57
  • Possible duplicate of [Android: Add a textview to linear layout programmatically](https://stackoverflow.com/questions/3204852/android-add-a-textview-to-linear-layout-programmatically) – HB. Jul 19 '17 at 17:00
  • Possible duplicate of [How can I add a TextView to a LinearLayout dynamically in Android?](https://stackoverflow.com/questions/4203506/how-can-i-add-a-textview-to-a-linearlayout-dynamically-in-android) – S.R Jul 19 '17 at 17:40

1 Answers1

3

Try to add below lines of code:

LinearLayout linearLayout =  (LinearLayout) findViewById(R.id.linear_layout_id);

TextView tv = new TextView(this);
tv.setText("hallo hallo");
tv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));

linearLayout.addView(tv);
Vishal Yadav
  • 3,642
  • 3
  • 25
  • 42
Rohit Singh
  • 411
  • 3
  • 15