AlertDialog getActivity()错误

时间:2015-12-18 23:52:53

标签: java android onclicklistener alertdialog

我正在构建一个使用AlertDialog的Android应用。我正在按照谷歌的指南来构建一个AlertDialog,但它一直给我一个错误。我在FAB上设置了一个onClickListener,但它要么永远不会工作,要么就会抛出错误。

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab2);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

            builder.setMessage("This is an alert dialog.").setTitle("alert dialog");
            builder.create();
        }
    });

}

但Android Studio会抛出错误,说: “错误:找不到符号方法getActivity()”

我已经尝试声明一个上下文变量并传递它,尝试使用getApplicationContext()和getApplication(),但它们都不起作用。

我做错了什么?

3 个答案:

答案 0 :(得分:1)

一切似乎都是正确的,但代码中需要进行一些小的调整。

如果要在活动使用Activity.this 中显示警告对话框,如果它在片段中,则在初始化AlertDialog.Builder期间使用getActivity() (*****)。

将警报对话框的逻辑写入单独的函数,并在clicklistener中调用它们。下面的代码将帮助您。

void showAlert(){

// If using activity use this 
AlertDialog.Builder adb = new AlertDialog.Builder(*YOUR ACTIVITY NAME*.this);

// If using Fragment use this 
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());

adb.setMessage("Alert Dialog Welcomes You");
adb.setTitle("Google alert dialog");  
AlertDialog ad = adb.create();
ad.show();
}

然后在你的fab onclicklistener中调用它。

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab2);
fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
           showAlert();
    }
});

快乐编码.. !!

答案 1 :(得分:0)

Android Studio似乎在某种程度上被窃听。我会尝试通过选择" invalidate caches / restart"来解决这个问题。从文件菜单。

也就是说,您也可以通过从视图中获取上下文来获取上下文。

  jQuery(document).ready(function ($) {
                $("#dialog").dialog({
                    autoOpen: false, 
                    show: {
                        effect: "blind",
                        duration: 1000
                    },

                hide: {
                    effect: "explode",
                    duration: 1000
                }
            });

            $("#opener").click(function () {
                $("#dialog").dialog("open");
            });
            $("#Closer").click(function () {
                $("#dialog").dialog("close");
            });
        });

 <div id="dialog" title="Basic dialog">
  <p>This is an animated dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
   <button id="Closer">Close Dialog</button>
</div>

答案 2 :(得分:0)

如果您的课程延伸至活动,您应该声明如下

AlertDialog.Builder builder = new AlertDialog.Builder(ActivityName.this);

如果延伸到片段

 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());