我想添加一个Button
to the main_activity
使用java代码查看,那么我该怎么做呢?
我已经尝试过这段代码,不幸的是它不起作用
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
在设置 contentView 之前”。这是因为你的Views
存在于你的layout
所以你需要一个充气的layout
找到id
呼叫setContentView()
首先与layout
其中包含view
。然后你可以找到view
并添加你的Button
to it.
@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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)