我百分之百确定这将是一个新手问题,但它开始了……
有没有一种方法可以让我在一个活动中编写一个方法,并且能够从其他活动中访问它?
示例:我的应用程序中有六个活动,每个活动都有自己的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();
}那么,有没有一种方法可以在所有活动之间共享这个自定义方法,并在每个活动中按下按钮时运行它,以避免在我的应用程序中复制大量代码?
如果是这样的话,有没有我可能会碰到的坑?(一些菜单项将弹出对话框,其他菜单项将把用户带到一个新的活动)
发布于 2011-07-04 13:19:13
你在每个活动中都有相似的菜单项吗?例如,相同数量的项目但不同的行为?如果是..。创建一个覆盖onCreateOptionsMenu和onOptionsItemSelected()方法的BaseActivity怎么样?(正如您在上面的示例中所给出的)。您的所有活动都应该从该BaseActivity继承,然后覆盖菜单处理方法。例如:helpDialogGo()将转到新类。
因此,BaseActivity将具有onCreateOptionsMenu和onOptionsItemSelected()方法。加上所有的menuItem操作(如helpDialogGo()等)作为空方法。继承的类将覆盖menuItem操作。
如果每个活动中的菜单项不相似,则最好为每个活动创建菜单。
编辑:
不知道你还想要什么。我想我说得很清楚了。让我再试一次。
类BaseActivity扩展了Activity。
BaseActivity extends Activity {
// Copy your onCreateOptionsMenu() and onOptionsItemSelected() methods here
protected void helpDialogGo() { }
// ... other methods
}类MyActivity1扩展了BaseActivity。
MyActivity1 extends BaseActivity {
// Copy your helpDialogGo() code in full here and then make
// any specific changes to menu behaviour based on activity.
}类MyActivity2扩展了BaseActivity
MyActivity2 extends BaseActivity {
// Copy your helpDialogGo() code in full here and then make
// any specific changes to menu behaviour based on activity.
}发布于 2011-07-04 10:34:37
当然,一种方法是创建一些封装了所需功能的自定义类-并在您的活动中使用这些类。这比将实现直接放在活动本身中(所有东西都是相同的,并且基于您到目前为止所描述的)是更好的抽象。
任何时候,你发现自己在复制一个隐含,这是一个提醒你的标志,这是一个很好的地方,将代码放入它自己的类中-通常是这样。
https://stackoverflow.com/questions/6566804
复制相似问题