1

我有以下问题:我想创建按钮和文本视图而不在 xml 文件中声明它们。我需要的按钮数量总是可变的,我想使用按钮来打开和关闭文本视图。按钮和文本视图应按照我创建它们的确切顺序在线性布局中创建。希望你能理解我

     final LinearLayout linL = (LinearLayout) findViewById (R.id.linearLayout1);


     TextView a1 = new TextView(this);
     a1.setText("Dynamic layouts ftw!");
     a1.setVisibility(View.VISIBLE);
     linL.addView(a1);

这是我到目前为止所尝试的:线性布局是在 xml 文件中创建的,并且已经包含一些元素。当我尝试运行它时,一切都很好,但是一旦我执行 linL.addView(a1) 我得到一个空指针异常

干杯,克里斯托夫

4

4 回答 4

0

使用 setlayoutparams。可能会有所帮助

TextView txtTag = new TextView(this);
    txtTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    txtTag.setText("Button " + (j + 1 + (i * 4));
    txtTag.setId(j + 1 + (i * 4));
    linL.addView(txtTag);
于 2012-11-14T10:20:21.743 回答
0
    try this structure whenever you want to create any thing dynamically.

    public class PhrasesActivity extends Activity {


        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.phrases);
            LinearLayout linearLayout = (LinearLayout) findViewById(R.id.LinearLayout1);

            LinearLayout L2 = new LinearLayout(this);
            L2.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            L2.setGravity(Gravity.CENTER);


            TextView a1 = new TextView(this);
            a1.setText("Dynamic layouts ftw!");
            a1.setVisibility(View.VISIBLE);

            Button b1 = new Button(this);
            b1.setText("SUBMIT");

            L2.addView(a1,(new LayoutParams(0,LayoutParams.WRAP_CONTENT,0.8f)));
            L2.addView(b1,(new LayoutParams(0,LayoutParams.WRAP_CONTENT,0.8f)));

            linearLayout.addView(L2);


        }
    }
Let me know you understand or not?
于 2012-11-14T10:39:09.717 回答
0

确保您的 XML 文件具有您想要添加按钮的视图设置

<LinearLayout
android:id="@+id/myName">

在您输入的活动中:

LinearLayout ll = (LinearLayout) findViewById(R.id.myName);
Button extra = new Button(this);
extra.setText("extra");
ll.addView(extra);

如果需要,您现在可以创建一个循环来添加内容

于 2014-01-11T16:13:59.337 回答
-1

您需要将 ID 添加到 XML 文件中的 LinearLayout:

<LinearLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="@dimen/x5" android:orientation="vertical" >
于 2012-11-14T10:42:06.910 回答