2016-09-14 90 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,我不知道他們必須按順序排列。我還學到了另外一件事,並且你讓我度過了一天。我正在洗澡,然後我將其設置爲正確的答案。我就是愛你! –