Search code examples
androidandroid-fragmentsandroid-listfragment

MainActivity with ActionBar and ListFragment


Basically I've got an ActionBarActivity that loads activity_main.xml which contains my ListFragment
My ActionBar has an Add button on it, to add items to the list.
Problem I've run into now, is how do I handle the Add and pass the information to the ListFragment to populate the ListView?

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //activity_main only contains <fragment ... /> to add my ListFragment
    }
    ....
    // This is called from onOptionsItemSelected
    private void showAddDialog() {
        FragmentManager fm = getSupportFragmentManager();
        InputDialog inputDialog = new AddInputDialog();
        inputDialog.setOnUpdateListener(new InputDialog.onUpdateListener(){
            @Override
            public void onUpdate(Item item){
                //I'm lost at what to do here...
            }
        });
        inputDialog.show(fm, "fragment_dialog_input");
    }

EDIT
Got it working using findFragmentById(), and posted answer below. I kept trying to get it to work using findFragmentByTag() and even though I had a TAG set in my fragment, and when debugging it(the TAG) showed correctly, for some reason would always return null.


Solution

  • Since the fragment is defined in activity_main.xml use findFragmentById using the specified android:id then you can call your public function within the ListFragment to update the list and notify adapter.

    private void showAddDialog() {
        final FragmentManager fm = getSupportFragmentManager();
        InputDialog inputDialog = new AddInputDialog();
        inputDialog.setOnUpdateListener(new InputDialog.onUpdateListener(){
            @Override
            public void onUpdate(Item item){
                ListFragment lf =  (ListFragment)fm.findFragmentById(R.id.listFragment);
                lf.addItem(item);
            }
        });
        inputDialog.show(fm, "fragment_dialog_input");
    }