Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 创建不带xml的按钮、文本视图_Android_Eclipse_Textview - Fatal编程技术网

Android 创建不带xml的按钮、文本视图

Android 创建不带xml的按钮、文本视图,android,eclipse,textview,Android,Eclipse,Textview,我有以下问题:我想创建按钮和文本视图,而不在xml文件中声明它们。我需要的按钮数量总是可变的,我想使用这些按钮来打开和关闭文本视图。按钮和文本视图应按照我创建它们时的确切顺序以线性布局创建。希望你能理解我 final LinearLayout linL = (LinearLayout) findViewById (R.id.linearLayout1); TextView a1 = new TextView(this); a1.setText("Dynamic

我有以下问题:我想创建按钮和文本视图,而不在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文件中创建的,allready包含一些元素。当我尝试运行它时,一切都很好,但只要执行linL.addView(a1),我就会得到一个空指针异常

干杯,
Christoph

使用setlayoutparams。b可以吗

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);

您需要将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" >

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


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

此代码发生在哪里?您以前确实膨胀过XML布局文件吗?是否膨胀过存在LinearLayout的布局?否则,findViewById将返回null,当您尝试添加TextView时,所有内容都将中断。你的线路上没有身份证Layoutah你是对的谢谢这对我很有用)如果linL是空的,我认为这不会有帮助
<LinearLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="@dimen/x5" android:orientation="vertical" >
<LinearLayout
android:id="@+id/myName">
LinearLayout ll = (LinearLayout) findViewById(R.id.myName);
Button extra = new Button(this);
extra.setText("extra");
ll.addView(extra);