我有這個MainActivity,會立即崩潰我的應用程序。這是爲什麼發生?我嘗試用Google的參考示例中的Context:Context aContext = getApplicationContext();
類型的對象將參數的「MainActivity.this」部分替換爲完全相同的結果。Toast對象崩潰應用程序
我在做什麼錯?
非常感謝。更新,以反映建議
package com.nactus.questionme;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button mMadridButton;
private Button mWrongButton;
private Toast aToast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// target the buttons
mMadridButton = (Button) findViewById(R.string.button_madrid);
mWrongButton = (Button) findViewById(R.string.button_wrong);
// set event listeners
mMadridButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Context context = getApplicationContext();
// my code goes here
aToast = Toast.makeText(context, "test", Toast.LENGTH_SHORT);
aToast.show();
}
});
mWrongButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Context context = getApplicationContext();
// my code goes here
aToast = Toast.makeText(context, "test", Toast.LENGTH_SHORT);
aToast.show();
}
});
}
}
代碼:死機一樣
出於好奇,它會崩潰馬上或者只有當你按下按鈕? –
@ tf.alves,馬上 – Nactus
好的,請在下面閱讀我的回答 –