如果我將setOnClickListener放在onCreate方法之外,此代碼不起作用。我想知道爲什麼?邏輯是正確的。但我得到一個紅色的錯誤中的onCreate以外的地方setOnClickListener()爲什麼setOnClickListener()必須在onCreate()中?
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button playbutton = (Button) findViewById(R.id.button1); // has to be in inside onCreate()
playbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"play",Toast.LENGTH_SHORT).show();
}
});
Button pausebutton = (Button) findViewById(R.id.button2); // has to be in inside onCreate()
pausebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"pause",Toast.LENGTH_SHORT).show();
}
});
}
}
你可以添加外部onCreate()方法的代碼嗎? – Avi