简体   繁体   English

将此传递给外部类并从Android上的alertdialog列表中启动活动

[英]passing this to an outer class and starting an activity from alertdialog's list on Android

I am developing an Android app, this app has a dozen of Activities, each one is for a corresponding screen. 我正在开发一个Android应用程序,这个应用程序有十几个活动,每个活动用于相应的屏幕。 Now I have this common subtitle bar on top of the screens. 现在我在屏幕上方有这个共同的字幕栏。 this subtitle bar has a button to display an alert dialog which shows link list to go to a different screen. 此字幕栏有一个按钮,用于显示警告对话框,显示链接列表以转到其他屏幕。

I could write a same function for each activity to call the alert dialog, but that would be tedious if I want to modify them, so I created this class: 我可以为每个活动编写一个相同的函数来调用警告对话框,但是如果我想修改它们会很繁琐,所以我创建了这个类:

public class MenuAlertDialog extends Activity {

/*
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
}
 */
public void createMenu(final Context context){
    AlertDialog.Builder dlg = new AlertDialog.Builder(context);
    dlg.setTitle("menu");

    String[] items = {"pageA", "pageB", "pageC", "pageD", "pageE"};
    dlg.setItems(items, new DialogInterface.OnClickListener(){
        @Override
        public void onClick(DialogInterface dialog, int which){
            switch(which){
            case 0:
                Intent intent = new Intent(context, MainActivity.class);
                startActivity(intent);
                break;
            default:
                break;

            }
        }
    });
    dlg.show();
}
}

and call it from each activity, like this: 并从每个活动中调用它,如下所示:

MenuAlertDialog menu = new MenuAlertDialog();
menu.createMenu(this);

from inside of onCreate. 从onCreate里面。

It can display the alertDialog, but whenever I press pageA link, it fails with an unexpected error. 它可以显示alertDialog,但每当我按pageA链接时,它都会因意外错误而失败。

Logcat says its a nullpointererror and the cause seems Logcat说它是一个nullpointererror和原因似乎

startActivity(intent);

What am I doing wrong? 我究竟做错了什么?

You should change the class to Extends Dialog and not activity. 您应该将类​​更改为“扩展对话框”而不是“活动”。 Also for Try this: 另外试试这个:

Check out this tutorial on how to create a custom dialog. 查看本教程,了解如何创建自定义对话框。 Custom Dialog Also Here Another Tutorial And Here 自定义对话框也在这里另一个教程这里

Remove the code 删除代码

extends Activity

as you have no need to extend your class that you are creating since it does not rely on any activity related functionality. 因为您不需要扩展您正在创建的类,因为它不依赖于任何与活动相关的功能。

Where you call startActivity(intent); 你在哪里调用startActivity(intent); replace it with 用它替换它

context.startActivity(intent);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM