Show dialog only using Context instead of Activity instance

后端 未结 4 984
轻奢々
轻奢々 2021-02-04 22:36

I could show dialog if I uses an Activity instance but when I uses Context or Application Context instance Dialog is not showing.

AlertDialog.Builder builder = n         


        
4条回答
  •  抹茶落季
    2021-02-04 23:10

    To use a context, it has to be passed from the activity on which the dialog is being created from. And this is only possible when you create your own dialog instead of using the AlertDialog.Builder provided by Java. Here is a custom one and we shall use it to get the application context.

    public class CustomDialogPopUp extends Dialog implements View.OnClickListener {
    
    public Activity a;
    public Context c;
    public Dialog d;
    //CUSTOMIZE YOUR DIALOG AS YOU LIKE
    RecyclerView pointAbsorber;
    ImageButton addPoint, attachPoint;
    EditText addContent;
    
    //VERY IMPORTANT CONSTRUCTOR THAT WE SHALL USE TO GET THE CONTEXT
    public CustomDialogPopUp(@NonNull Context context, Activity a, Context c) {
        super(context);
        this.a = a;
        this.c = c;
    }
    
    //INITIALIZING YOUR CUSTOM DIALOG VIEWS AND WHAT NOT. IT NEEDS AN XML FILE BY THE WAY
    public void initViewSnActions(){
        pointAbsorber = findViewById(R.id.pointsRV);
        addPoint = findViewById(R.id.addPoint);
        attachPoint = findViewById(R.id.attachPoint);
        addContent = findViewById(R.id.addContent);
        
    }
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.custom_dialog);
        initViewSnActions();
    }
    
    //ON CLICK LISTENER FOR YOUR VIEWS
    @Override
    public void onClick(View v) {
        
    }
    

    }

    To pass the application context, one has to initialize it in whichever class you want it to appear as follows. Note how the activity and the context is passed

    NotesPopUp notesPopUp = new NotesPopUp(PersistentTest.this, getParent(), getApplicationContext());
    notesPopUp.show();
    

提交回复
热议问题