Preeti Srivastava Preeti Srivastava - 2 months ago 18
Android Question

How to Display Dialog from a class extending BaseAdaper

I am trying to display a Tabbed Pager View in Dialog Box but I am unable to initialize

getSupportFragmentManager
in my Adapter Class which
extends BaseAdapter
. If I am using
MainActivity extends AppCompatActivity
then
getSupportFragmentManager
is not showing error. Here is my Code. Please guide me.

public class ContactListAdapter extends BaseAdapter {
------------
------------
slidingListItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TabDialogFragment.createBuilder(ContactListAdapter.this, getSupportFragmentManager())
.setTitle("Title")
.setSubTitle("Subtitle")
.setTabButtonText(new CharSequence[]{"Tab1", "Tab2"})
.setPositiveButtonText("Ok")
.setNegativeButtonText("Cancel")
.setNeutralButtonText("Neutral")
.setRequestCode(REQUEST_TABBED_DIALOG)
.show();
}
});


How can I initialize
getSupportFragmentManager()
in my Adapter Class ?

Answer

You can make a field in your adapter's class and save the FragmentManager like that, by passing it in the constructor of your adapter. Something like:

public class ContactListAdapter extends BaseAdapter { 

private FragmentManager mFragmentManager;

public ContactListAdapter(FragmentManager fragmentManager)
    mFragmentManager = fragmentManager;
}
 ------------
 ------------
slidingListItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            TabDialogFragment.createBuilder(ContactListAdapter.this, mFragmentManager)
                    .setTitle("Title")
                    .setSubTitle("Subtitle")
                    .setTabButtonText(new CharSequence[]{"Tab1", "Tab2"})
                    .setPositiveButtonText("Ok")
                    .setNegativeButtonText("Cancel")
                    .setNeutralButtonText("Neutral")
                    .setRequestCode(REQUEST_TABBED_DIALOG)
                    .show();
        }
    });

And when creating this adapter in your activity, create it like this:

ContactListAdapter mAdapter = new ContactListAdapter(getSupportFragmentManager());