【问题标题】:How to display an Alert Dialog in a fragment如何在片段中显示警告对话框
【发布时间】:2023-02-10 20:26:22
【问题描述】:

我正在尝试在片段中显示自定义警报对话框。我的片段的名字是 MoviesFragFragmentActivity.java

这是我的代码:

final AlertDialog dialog1 = new AlertDialog.Builder(MoviesFragFragmentActivity.this).create();
View inflate = getLayoutInflater().inflate(R.layout.custom3,null); 
dialog1.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog1.setView(inflate);
TextView t1 = (TextView) inflate.findViewById(R.id.t1);

TextView t2 = (TextView) inflate.findViewById(R.id.t2);

TextView t3 = (TextView) inflate.findViewById(R.id.t3);

LinearLayout b1 = (LinearLayout) inflate.findViewById(R.id.b1);

ImageView i1 = (ImageView) inflate.findViewById(R.id.i1);

LinearLayout bg = (LinearLayout) inflate.findViewById(R.id.bg);
t1.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/en_medium.ttf"), 0);
t2.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/sansation_regular.ttf"), 0);
t3.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/sansation_regular.ttf"), 0);
i1.setImageResource(R.drawable.splash);
i1.getDrawable().setColorFilter(Color.parseColor("#008DCD"), PorterDuff.Mode.SRC_IN);
t1.setText("Oh,No...");
t2.setText("This feature is not available yet, try after new update ");
t3.setText("Try again");
_rippleRoundStroke(bg, "#FAFAFA", "#000000", 40, 0, "#000000");
_CardView(b1, 10, 100, "#008DCD", true);
b1.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ 
        // Default item selected on bottom navigation onCreate
        bottomnavigation4.getMenu().findItem(2).setChecked(true);
        SketchwareUtil.showMessage(getApplicationContext(), "Try again later");
        dialog1.dismiss();
    }
});
dialog1.setCancelable(false);
dialog1.show();

在编译时,它给了我这个错误:

  1. /storage/emulated/0/.sketchware/mysc/680/app/src/main/java/com/liquidapps/movieapp/MoviesFragFragmentActivity.java 中的错误(第 601 行)

    final AlertDialog dialog1 = new AlertDialog.Builder(MoviesFragFragmentActivity.this).create(); 构造函数 AlertDialog.Builder(MoviesFragFragmentActivity) 未定义

    如何在片段中显示警报对话框?

    我尝试在一个活动(Main activity.java)中使用相同的代码并且它工作正常,但是一旦我在片段中使用代码,我就会收到错误。

【问题讨论】:

    标签: java android dialog fragment


    【解决方案1】:

    您遇到的错误是因为您尝试使用 MoviesFragFragmentActivity 实例创建 AlertDialog,但在片段内创建 AlertDialog 的正确方法是使用片段所附加的 Activity 的上下文。要解决此问题,您可以使用 getActivity() 方法获取片段附加到的 Activity 的上下文,并将其用作 AlertDialog 的上下文。这是更新后的代码:

    只需替换这一行

    final AlertDialog dialog1 = new AlertDialog.Builder(getActivity()).create();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-13
      • 2015-01-03
      • 1970-01-01
      • 1970-01-01
      • 2016-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多