我100%確定這將是其中一個新手問題,但這裏它去...通過應用程序可用的方法?
有沒有一種方法,我可以在一個活動中寫一個方法,並能夠從其他?
例子: 我在我的應用程序6個activites,每個都有它自己的menu.xml文件,因爲可用於每個選項需要是不同的,我有這些菜單&的菜單項設置,如下所示:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.calculator_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//Handle item selection
switch (item.getItemId()) {
case R.id.menuItem_calculator_Help:
helpDialogGo();
return true;
case R.id.menuItem_calculator_Settings:
//settingsActivityGo();
return true;
case R.id.menuItem_calculator_Share:
shareGo();
return true;
case android.R.id.home:
// app icon in Action Bar clicked; go home
Intent uptohome = new Intent(this, Main.class);
uptohome.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(uptohome);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
所述的這些方法之一的例子是:
private void helpDialogGo() {
Toast.makeText(this, "help", Toast.LENGTH_LONG).show();
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("Sorry, no help has been written since this application is still in development. This is a prerelease version.")
.setCancelable(false)
.setPositiveButton("Cool", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'Yes' Button
dialog.cancel();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("Pixel Help");
// Icon for AlertDialog
alert.setIcon(R.drawable.question);
alert.show();
}
所以是有辦法知道所有的活動間共享這個自定義的方法,並且當在它們中的每按下按鈕運行它,以避免有大量的金錢在我的應用程序中複製代碼?
如果是的話,是沒有辦法,我可以打任何坑窪? (某些菜單項會彈出對話框,其他人將用戶帶到一個新的活動)
這實際上是相當常見的做法。這不是特定於Android的內容,而是與類設計的最佳實踐更相關。 – omermuhammed
好的。在我開始之前,你能詳細闡述一下嗎? – rabbitt
@omermuhammed同意。 – GSree