【问题标题】:What should the Context be for Intent(Context, Class) in a dialog box?对话框中 Intent(Context, Class) 的上下文应该是什么?
【发布时间】:2014-01-18 14:12:17
【问题描述】:

我有一个对话框,我用它来在活动之间切换(当抛出错误时)。我习惯使用Intent(this, class) 在活动之间切换,但是在DialogBox 中,上下文应该是什么而不是“this”。

我的代码:

package com.example.partyorganiser;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

public class Attendance_Dialog extends DialogFragment {
    Context context;
     public Attendance_Dialog(Context c){
         this.context = c;
     }
     public Dialog onCreateDialog(Bundle savedInstanceState, final Context context) {
            // Use the Builder class for convenient dialog construction
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage("NEED TO CREATE A PARTY FIRST: MENU OR ADD A PARTY")
                   .setPositiveButton("MENU", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                          Intent switch_menu = new Intent(context, MenuList.class);
                       }
                   })
                   .setNegativeButton("ADD A PARTY", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                           Intent switch_addparty = new Intent(context , AddParty.class);
                           startActivity(switch_addparty);
                       }
                   });
            // Create the AlertDialog object and return it
            return builder.create();
        }
}

【问题讨论】:

  • youractivityName.this
  • 得到错误“在范围内没有可以访问类型(我的类)的封闭实例。
  • 正常活动,如果我添加它,它不会增加任何问题,我想???感谢您的帮助!

标签: android android-intent dialog android-alertdialog android-context


【解决方案1】:

将上下文传递给对话框。

public class MyDialog extends Dialog{
    Context context;
    //Constructor
    public MyDialog(Context c){
        this.context = c;
    }

    //Example of using the context
    public void doSomethingWithContext(){
        Intent i = new Intent(this, MyClass.class);
    }
} 

//Creating MyDialog and giving it a context
MyDialog md = new MyDialog(this);
md.show();

在片段中,您可以使用getActivity() 从您开始片段的活动中获取上下文。

【讨论】:

    猜你喜欢
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多