View Pager context issues

Within my MainActivity, I am trying to get the context of a control (spinner) that is located on a fragment. I am using a FragmentStatePagerAdapter to manage the fragment(s). The last line of my onCreate() throws the exception because the mSpinner keeps returning a null. Ive tried that line two different ways, as shown and:

mSpinner = (Spinner) mVP.findViewById(R.id.spinner1);

I am assuming that my context is incorrect but don't have the experience to know how to fix without blindly guessing. Thanks for any constructive help you can offer in advance! :)

My code looks like this:

public class MainActivity extends FragmentActivity {
    MyAdapter mAdapter;
    ViewPager mVP;
    Spinner mSpinner;
    Spinner.OnItemSelectedListener onSpinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mAdapter = new MyAdapter(getSupportFragmentManager());
        mVP = (ViewPager) findViewById(R.id.viewPager);
        mVP.setAdapter(mAdapter);
        mSpinner = (Spinner) findViewById(R.id.spinner1);
    }

    public static class MyAdapter extends FragmentStatePagerAdapter {
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return 5;
        }

        @Override
        public Fragment getItem(int pos) {
            switch (pos) {

                case 0:return FirstFragment.newInstance("FirstFragment, Instance 1");
                case 1:return SecondFragment.newInstance("SecondFragment, Instance 1");
                case 2:return ThirdFragment.newInstance("ThirdFragment, Instance 1");
                case 3:return ThirdFragment.newInstance("ThirdFragment, Instance 2");
                case 4:return ThirdFragment.newInstance("ThirdFragment, Instance 3");
                default:return ThirdFragment.newInstance("ThirdFragment, Default");
            }
        }
    }
}

Answers


You can get Your Fragment view this way and then use Fragment's view to find Spinner using findViewById().

Try this.

View fragment_view = getLayoutInflater().inflate(R.layout.fragment_view, null);
Spinner mSpinner = (Spinner) fragment_view.findViewById(R.id.spinner1);

I hope it helps!


I am trying to get the context of a control (spinner) that is located on a fragment.

This is not going to work:

mSpinner = (Spinner) findViewById(R.id.spinner1);

Because one of your fragments contains the spinner, so you have to get the spinner reference from the fragment, not from the activity!


Need Your Help

Dynamic RSpec spec generation

ruby dynamic rspec specifications

I'd like to generate a series of specs dynamically based on an external data source. Specifically, I have a Google Spreadsheet that's downloaded, and each row in the spreadsheet should be used for ...