警报对话框没有响应?

时间:2017-08-21 09:05:27

标签: android android-layout alertdialog

我正在尝试开发一个应用程序,其中必须在recylcerview按钮点击时打开alertdialog,这些是我得到的错误:

21 06:50:20.817 1037-1037/com.example.hephaestus.shadowpets4 
E/AndroidRuntime: FATAL EXCEPTION: main                                                                         
java.lang.IllegalStateException: You need to use a Theme.AppCompat 
theme (or descendant) with this activity.                                                                             
      at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:359)
      at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
      at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:289)
      at android.support.v7.app.AppCompatDialog.setContentView(AppCompatDialog.java:83)
      at android.support.v7.app.AlertController.installContent(AlertController.java:225)
      at android.support.v7.app.AlertDialog.onCreate(AlertDialog.java:257)
      at android.app.Dialog.dispatchOnCreate(Dialog.java:351)
      at android.app.Dialog.show(Dialog.java:256)
      at com.example.hephaestus.shadowpets4.Adapters.TrainerAdapter$1.onClick(TrainerAdapter.java:84)
      at android.view.View.performClick(View.java:4084)
      at android.view.View$PerformClick.run(View.java:16966)
      at android.os.Handler.handleCallback(Handler.java:615)
      at android.os.Handler.dispatchMessage(Handler.java:92)
      at android.os.Looper.loop(Looper.java:137)
      at android.app.ActivityThread.main(ActivityThread.java:4745)
      at java.lang.reflect.Method.invokeNative(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:511)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
      at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

经过大量研究后,我发现我的问题的答案是在你的活动中使用警告对话框,我们应该在创建警告对话框时使用活动而不是上下文,我们应该在使用片段时使用应用程序上下文,这些更改必须在适配器(因为我将它与recylcerview一起使用)以及它执行的活动,这个例子可以理解:  以下是使用片段

中的recyclerview实现警告对话框的示例
  public class AdoptpetAdapter extends RecyclerView.Adapter<AdoptpetAdapter.ViewHolder> {
     private Context context;
     private List<Pet> petList;
    public AdoptpetAdapter(Context context,List<Pet> petList)
    {
        this.context=context;
        this.petList=petList;
    }
    @Override
    public AdoptpetAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_pet,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
            holder.petName.setText(petList.get(position).getPetName());
            holder.petCost.setText(petList.get(position).getPetCost());
        Picasso.with(context).load(petList.get(position).getPetImage()).into(holder.imageView);
        holder.btn_Contact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                  LayoutInflater li =LayoutInflater.from(context);
               View promptsView = li.inflate(R.layout.petenquiryform,null);
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setView(promptsView);
                  TextView msg_Title =(TextView)promptsView.findViewById(R.id.txt_petEnquirytitle);
                    msg_Title.setText("Enquiry about "+" "+petList.get(position).getPetName());
                EditText txt_message =(EditText) promptsView.findViewById(R.id.txt_message);
                 builder.setCancelable(false)
                         .setPositiveButton("Send", new DialogInterface.OnClickListener() {
                             @Override
                             public void onClick(DialogInterface dialog, int which) {

                             }
                         })
                         .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                             @Override
                             public void onClick(DialogInterface dialog, int which) {

                             }
                         });
                   AlertDialog alertDialog = builder.create();
                    alertDialog.show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return petList.size();
    }
    public class ViewHolder extends RecyclerView.ViewHolder
    {
        private ImageView imageView;
        private TextView petCost,petName;
        private Button btn_Contact;

        public ViewHolder(View itemView) {

            super(itemView);
            imageView=(ImageView)itemView.findViewById(R.id.img_pet);
            petCost=(TextView)itemView.findViewById(R.id.txt_petprice);
            petName=(TextView)itemView.findViewById(R.id.txt_petname);
            btn_Contact=(Button)itemView.findViewById(R.id.btn_contactSeller);
        }
    }
}

要在片段中实现它,您只需执行以下代码

    public class Pets extends Fragment {
    List<Pet> petList;
    RecyclerView recyclerView;
    ProgressDialog pDialog;
    AdoptpetAdapter adapter;




    public Pets() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_pets, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recyclerView=(RecyclerView)view.findViewById(R.id.list_pets);
         initviews();
    }
    private void initviews()
    {
        pDialog = new ProgressDialog(getContext());
        pDialog.setMessage("Loading,Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();
        try
        {
            Glide.with(this).load(R.drawable.ic_menu_gallery).into((ImageView) recyclerView.findViewById(R.id.img_pet));

        }
        catch (Exception ex)
        {

        }
        petList=new ArrayList<>();
        adapter=new AdoptpetAdapter(getContext(),petList);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(),2);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
        loadJson();
    }
    private void loadJson()
    {
          try
          {
              Retrofit retrofit = new Retrofit.Builder().baseUrl(APIUrl.BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
              APIService service=retrofit.create(APIService.class);
              Call<Response> call =service.getPetList();
               call.enqueue(new Callback<Response>() {
                   @Override
                   public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
                       List<Pet>data=response.body().getPetList();
                       recyclerView.setAdapter(new AdoptpetAdapter(getActivity(),data));
                       recyclerView.smoothScrollToPosition(0);
                       pDialog.hide();
                   }

                   @Override
                   public void onFailure(Call<Response> call, Throwable t) {
                       pDialog.dismiss();


                   }
               });
          }
          catch (Exception ex)
          {
               pDialog.hide();

          }
    }
}

**在Activity中实现它时,应该如下更改,以下是适配器的代码并在其中实现警告对话框**

public class TrainerAdapter extends RecyclerView.Adapter<TrainerAdapter.ViewHolder> {
    private Activity activity;
    private List<Trainer> trainerList;
    public TrainerAdapter(Activity activity,List<Trainer> trainerList)
    {
        this.activity=activity;
        this.trainerList=trainerList;
    }
    @Override
    public TrainerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_trainer,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.trainerName.setText(trainerList.get(position).getTrainerName());
        holder.trainerLocation.setText(trainerList.get(position).getTrainerPhone());
        holder.btnEnquiretrnr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LayoutInflater li = LayoutInflater.from(activity);
               View promptsView = li.inflate(R.layout.trainerenquiryform,null);
                AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                 builder.setView(promptsView);
                 builder.setCancelable(false)
                         .setPositiveButton("Send", new DialogInterface.OnClickListener() {
                             @Override
                             public void onClick(DialogInterface dialog, int which) {

                             }
                         })
                         .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                             @Override
                             public void onClick(DialogInterface dialog, int which) {

                             }
                         });
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
            }
        });

    }

    @Override
    public int getItemCount() {
        return trainerList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private TextView trainerName,trainerLocation;
        private Button btnEnquiretrnr;
        public ViewHolder(View itemView) {
            super(itemView);
            trainerName=(TextView)itemView.findViewById(R.id.txt_Trainername);
            trainerLocation=(TextView)itemView.findViewById(R.id.txt_trainerLocation);
            btnEnquiretrnr=(Button)itemView.findViewById(R.id.btn_enquireTrnr);
        }
    }
}

为了将其实施到活动中,我们应该如何实施

   public class Trainers extends AppCompatActivity {
        RecyclerView trainersList;
        List<Trainer> list;

        ProgressDialog pDialog;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_trainers);
            pDialog = new ProgressDialog(this);
            pDialog.setCancelable(false);
            pDialog.setMessage("Loading,Please wait....");
            pDialog.show();
            trainersList =(RecyclerView)findViewById(R.id.list_trainers);
            trainersList.setHasFixedSize(true);

            RecyclerView.LayoutManager layoutManager= new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.VERTICAL,false);
            trainersList.setLayoutManager(layoutManager);
            loadData();

        }

        private void loadData()
        {
            try {
                Retrofit retrofit = new Retrofit.Builder().baseUrl(APIUrl.BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
                APIService service = retrofit.create(APIService.class);
                Call<Response> call = service.getTrainers();
                call.enqueue(new Callback<Response>() {
                    @Override
                    public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
                        list=response.body().getTrainerList();
                        TrainerAdapter trainerAdapter=new TrainerAdapter(Trainers.this,list);
                        trainersList.setAdapter(trainerAdapter);
                        pDialog.hide();
                    }

                    @Override
                    public void onFailure(Call<Response> call, Throwable t) {

                    }
                });
            }
             catch (Exception ex)
             {

                }
            }
        }

我希望这些答案能让很多人像我一样查询