2016-09-14 133 views
0

我离开你的代码:这个Android应用程序为什么立即崩溃?

public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    RelativeLayout layout = (RelativeLayout)findViewById(R.id.disposizione); 
    Button pulsante = new Button(this); 
    pulsante.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)); 
    pulsante.setText("Click me"); 
    pulsante.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View view) { 
      Toast.makeText(MainActivity.this, "Thug life bitch!", Toast.LENGTH_LONG).show(); 
     } 
    }); 

    layout.addView(pulsante); 
    setContentView(R.layout.main); 
} 

我试图删除从RelativeLayout的所有行到layout.addView之一,因此它再次工作!

这段代码有什么问题?我必须说我没有得到任何构建错误或警告。

在此先感谢。

回答

3

setContentView()后立即super.onCreate()

super.onCreate(savedInstanceState); 

setContentView(R.layout.main); 
+1

OMG,我不知道他们必须按顺序排列。我还学到了另外一件事,并且你让我度过了一天。我正在洗澡,然后我将其设置为正确的答案。我就是爱你! –