我正在尝试在 LinearLayout 中以编程方式创建 TextView。该程序包括一个检查系统,用于检查是否已添加,并且创建 TextView 的提示是微调器中的一个选项。这是微调器的完整 onClick 方法
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 布局中识别出来的。
final LinearLayout mainll = (LinearLayout) getActivity().findViewById(R.id.main);
尽管没有识别出编码错误,但从菜单中选择番茄酱后,应用程序崩溃了。任何有关此问题的帮助将不胜感激。
最佳答案
尝试添加以下代码行:
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);
关于java - 如何在线性布局中以编程方式创建 TextView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45196556/