使用Java代码在main_activity视图中添加按钮
问题描述:
我想使用java代码将Button
添加到main_activity
视图,那么我该怎么做呢? 我已经尝试过此代码,不幸的是它没有工作使用Java代码在main_activity视图中添加按钮
public class MainActivity extends Activity {
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout l1 = ((RelativeLayout)this.findViewById(R.id.view1));
btn = new Button(this);
btn.setText(R.string.hello_world);
l1.addView(btn);
setContentView(l1);
}
}
答
正如艾哈迈德说,“设定内容查看之前,您不能调用findViewById
”。这是因为您的Views
存在于您的layout
之内,因此您需要用一个充气的layout
找到id
英寸。请致电setContentView()
先用layout
其中包含view
。然后,您可以找到view
并将其添加到Button
。
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
RelativeLayout l1 = (RelativeLayout) findViewById(R.id.view1);
btn = new Button(this);
btn.setText(R.string.hello_world);
l1.addView(btn);
}
+0
谢谢:)它正常工作:) –
在设置contentView之前,您无法调用'findViewById'。 – Ahmad