【问题标题】:Android open AlertDialog from another activityAndroid从另一个活动打开AlertDialog
【发布时间】:2012-08-05 12:08:41
【问题描述】:

我在此处和其他网站上阅读了相互矛盾的报告,这些报告说可以/不可能显示来自其他活动的警报对话框。我正在尝试这样做:

public class Options extends Activity {

    /** Include classes */
    SharedPreferences sharedPrefs;
    Preferences prefs;
    Location loc;
    LocationSQL locSQL;
    NetworkConnection netConnect;

    /** Declare buttons */
    Button bLocation;
    Button bRefresh;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.options);

        sharedPrefs = PreferenceManager.getDefaultSharedPreferences(Options.this);

        /** Set the location for the user */
        setLocationPref();

        /** Refresh selection */
        bRefresh = (Button) findViewById(R.id.bRefresh);
        bRefresh.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
        loc = new Location(getApplicationContext());
            try{

                loc.locationSelection();
            }catch (Exception e){
                Log.d("ERROR", "Catch " + e);
            }
            }
        });

        /** Location selection */
        bLocation = (Button) findViewById(R.id.bLocation);
        bLocation.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

            }
        });
    }
}

然后我想做一些处理,如果需要调用一个 AlertDialog 框。但我得到下面的错误。我知道如果我是正确的,我正在使用已被破坏的上下文?但我想不出如何解决这个问题?

public class Location {

    private static final String Context = null;
    NetworkConnection nc;
    SharedPreferences getSharedPrefs;
    SharedPreferences putSharedPrefs;
    NetworkConnection netConnect;
    Options opts;
    Context context;

    public Location (Context arg)
    {
        context = arg;
    }

    public void locationSelection(){

        message();

    }

    public void message(){

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
        alertDialogBuilder.setTitle("Your Title");
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();

    }

}

Catch android.view.WindowManager$BadTokenException: Unable to add window -- token null 不适用于应用程序。

非常感谢您的帮助:-)

【问题讨论】:

    标签: android android-activity android-alertdialog


    【解决方案1】:

    不要将 getApplicationContext() 传递给 Location 构造函数,而是尝试传递 YourClass.this(这里是 Options.this)。

    另外,这行代码是什么?

    private static final String Context = null;
    

    【讨论】:

    • 谢谢,这似乎有帮助,我以为我试过了:/那行代码是复制和粘贴错误,它不应该在那里,谢谢你的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 2013-05-26
    • 2012-01-04
    • 1970-01-01
    • 1970-01-01
    • 2012-12-28
    相关资源
    最近更新 更多