【问题标题】:How can I create a TextView programmatically in a Linear Layout?如何在线性布局中以编程方式创建 TextView?
【发布时间】:2017-12-25 01:54:03
【问题描述】:

我正在尝试在 LinearLayout 中以编程方式制作 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);

尽管没有识别出编码错误,但从菜单中选择番茄酱时,应用程序会崩溃。对此问题的任何帮助将不胜感激。

【问题讨论】:

标签: java 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多