2017-07-19 159 views
0

我想在LinearLayout中以編程方式製作TextView。該程序包含一個檢查系統來檢查它是否已經被添加,並且創建文本視圖的提示是微調器中的一個選項。下面是所說的紡絲器如何在線性佈局中以編程方式創建TextView?

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; 

      } 

     } 

線性佈局是從當應用程序在一個單獨的方法啓動的XML佈局識別的充分的onClick方法。

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

該應用程序崩潰後,從菜單中選擇番茄醬儘管缺乏確定的編碼錯誤。任何有關這個問題的幫助將不勝感激。

+0

指的https://stackoverflow.com/questions/3204852/android-add-a-textview-to-linear-layout-programmatically – sasikumar

+0

可能的複製[Android:以編程方式向線性佈局添加textview](https://stackoverflow.com/questions/3204852/android-add-a-textview-to-linear-layout-programmatically) –

+0

可能的重複[如何添加在Android中動態使用TextView到LinearLayout?](https://stackoverflow.com/questions/4203506/how-can-i-add-a-textview-to-a-linearlayout-dynamically-in-android) –

回答

1

嘗試添加下面的代碼行:

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); 
相關問題