Android MaterialDialog Spinner

2019-08-01 10:20发布

问题:

I'm using MaterialDialog.Builder to show a dialog. I set a customView for my dialog.

In my layout i have a spinner and i want to populate it form my sqlite database when i show the dialog.

The callback function only works when i push those buttons. Is there a function that i can use before dialog shows and use the layout that i set to append the spinner ?

My code is like :

boolean wrapInScrollView = true;
new MaterialDialog.Builder(mContext)
.customView(layout, wrapInScrollView)
.autoDismiss(false)
.negativeText(R.string.text40)
.positiveText(buton)
.callback(new MaterialDialog.ButtonCallback() { ....})
.build()
.show();

Thanks

回答1:

Assume that you have LinearLayout and inside you have Spinner:

  • custom xml file name is "dialogCustom"
  • linearlayout id inside it is "linearLayoutMine"
  • spinner id inside linearlayout is "mySpinner"

    MaterialDialog.Builder md=new MaterialDialog.Builder(this);
    
    LayoutInflater factory = LayoutInflater.from(this);
    final View stdView = factory.inflate(R.layout.dialogCustom, null);
    LinearLayout linearLayoutMine (LinearLayout) stdView.findViewById(R.id.linearLayoutMine);
    Spinner spinner = (Spinner) linearLayoutMine.findViewById(R.id.mySpinner);
    
    //Load items to spinner
    
    md.title("myTitle")
      .customView(linearLayoutMine, wrapInScrollView)
      .autoDismiss(false)
      .negativeText(R.string.text40)
      .positiveText(buton)
      .callback(new MaterialDialog.ButtonCallback() { ....})
      .build()
      .show();
    

Callbacks are only for when positive, negative buttons are pressed.



回答2:

Another possibility is to separate build() and show() calls and use getCustomView() after build().

Like this

dlg = new MaterialDialog.Builder(mContext)
    .customView(layout, wrapInScrollView)
    .autoDismiss(false)
    .negativeText(R.string.text40)
    .positiveText(buton)
    .callback(new MaterialDialog.ButtonCallback() { ....})
    .build();


mySpinner = (Spinner)dlg.getCustomView.findViewById(R.id.mySpinner);
// do whatever you need to do with your spinner

// finally show the dialog
dlg.show();

This is not necessarily better than the approach suggested by Jemshit, just a different way to achieve the result.