由网友(遥遥江上客)分享简介:我想添加一个按钮到 main_activity 视图用java code,所以我怎么能做到这一点?我已经尝试过这种code和遗憾的是它没有工作公共类MainActivity延伸活动{按钮BTN;@覆盖保护无效的onCreate(包savedInstanceState){super.onCreate(savedInst...
我想添加一个按钮
到 main_activity
视图用java code,所以我怎么能做到这一点?
我已经尝试过这种code和遗憾的是它没有工作
公共类MainActivity延伸活动{
按钮BTN;
@覆盖
保护无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
RelativeLayout的L1 =((RelativeLayout的)this.findViewById(R.id.view1));
BTN =新的按钮(这一点);
btn.setText(R.string.hello_world);
l1.addView(BTN);
的setContentView(L1);
}
}
解决方案
由于艾哈迈德说,你不能叫 findViewById
设置内容查看之前。这是因为你的浏览
的布局中存在
,所以你需要一个充气布局
发现,在 ID
呼叫的setContentView()
先用布局
包含视图
。然后,你可以找到视图
和您的按钮
添加到它。
@覆盖
保护无效的onCreate(包savedInstanceState)
{
super.onCreate(savedInstanceState);
的setContentView(R.layout.your_layout);
RelativeLayout的L1 =(RelativeLayout的)findViewById(R.id.view1);
BTN =新的按钮(这一点);
btn.setText(R.string.hello_world);
l1.addView(BTN);
}
I want to add a Button
to the main_activity
view using java code , so how can i do it ?
I have already tried this code and unfortunately it didn't work
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);
}
}
解决方案
As Ahmad has said, "You can't call findViewById
before setting the contentView". This is because your Views
exist within your layout
so you need an inflated layout
to find the id
in. Call setContentView()
first with the layout
which contains view
. Then you can find the view
and add your 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);
}
相关推荐
最新文章