The layout
may not have been completely finished drawing. Try posting a runnable
on it. Something like
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout layout_principal=(LinearLayout)findViewById(R.id.pru);
layout_principal.post(new Runnable()
{
public void run()
{
int mywidth=layout_principal.getWidth();
LinearLayout.LayoutParams txt_sep_principal_Params=new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
mywidth/2);
TextView txt_sep_principal=new TextView(this);
...
}
});
Edit
public class YourActivty extends Activity
{
// These are declarations
TextView tv;
Button btn;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// these are initializations
tv = (TextView) findViewById(R.id.someId);
btn = (Button) findViewById(R.id.someOtherId);
See the comments in my code. Declaring them this way makes them available to the whole Activity
. You can't initialize them before calling setContentView()
and certainly not outside of a method. Obviously, you need to replace the sample View
s I have used with your own.