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