我有以下问题:我想创建按钮和textview而不在xml文件中声明它们。我需要的按钮数量总是可变的,我想使用按钮来打开和关闭文本视图。按钮和Textview应按照我创建它们的确切顺序在linearLayout中创建。希望你了解我
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)即时获取空指针异常
欢呼声, 克里斯托弗
答案 0 :(得分: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);
答案 1 :(得分: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?
答案 2 :(得分:0)
确保您的XML文件具有要添加按钮的视图设置(s)
<LinearLayout
android:id="@+id/myName">
在您键入的活动中:
LinearLayout ll = (LinearLayout) findViewById(R.id.myName);
Button extra = new Button(this);
extra.setText("extra");
ll.addView(extra);
如果需要,您现在可以创建一个循环来添加内容
答案 3 :(得分:-1)
您需要在XML文件中将ID添加到LinearLayout:
<LinearLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="@dimen/x5" android:orientation="vertical" >