LinearLayout未显示以编程方式添加的项目

时间:2014-05-19 11:23:00

标签: android android-linearlayout

我试图以编程方式将文本视图和按钮添加到线性布局中。

按钮显示但文本视图不是。

这是我的代码:

        LinearLayout main = (LinearLayout) findViewById(R.id.mainlayout);
        LinearLayout first = new LinearLayout(this);

        LayoutParams fparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 5.0f);
        LayoutParams tvparams = new LayoutParams(0, LayoutParams.WRAP_CONTENT);
        LayoutParams btparams = new LayoutParams(0, LayoutParams.WRAP_CONTENT);

        first.setLayoutParams(fparams);
        first.setOrientation(LinearLayout.HORIZONTAL);

        TextView tv = new TextView(this);
        tvparams.weight = 3.0f;
        tv.setLayoutParams(tvparams);

        Button bt = new Button(this);
        btparams.weight = 2.0f;
        bt.setLayoutParams(btparams);

        first.addView(bt);
        first.addView(tv);      
        main.addView(first);

2 个答案:

答案 0 :(得分:1)

尝试在TextView上设置一些文字。使用它的setText()方法

答案 1 :(得分:0)

确定尝试以编程方式设置

        LinearLayout myLayout = (LinearLayout)findViewById(R.id.parent);
 LayoutParams fparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 5.0f);
        LayoutParams tvparams = new LayoutParams(0, LayoutParams.WRAP_CONTENT,3.0f);
        LayoutParams btparams = new LayoutParams(0, LayoutParams.WRAP_CONTENT,2.0f);
        LinearLayout first = new LinearLayout(this);
        first.setLayoutParams(fparams);
        first.setOrientation(LinearLayout.HORIZONTAL);

        TextView tv = new TextView(this);
        tv.setText("asdsad");
        tv.setLayoutParams(tvparams);

        Button bt = new Button(this);
        bt.setLayoutParams(btparams);

        first.addView(bt);
        first.addView(tv);      
        myLayout.addView(first);

希望它能帮助我,正确地为我工作。