使用选项卡滑动视图获取并更改当前片段布局

时间:2015-07-07 21:40:53

标签: android android-fragments android-viewpager

如何从带有滑动视图的选项卡中获取当前片段并从我的MainActivity中修改它的布局?可能吗?

在应用程序UI下面,我需要修改每个片段的背景,并在插入新条目时在运行时添加一个新的ImageView。

enter image description here

MainActivity

public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
        private ViewPager mViewPager;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            // Set up the action bar.
            final ActionBar actionBar = getSupportActionBar();
            actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

            // Create the adapter that will return a fragment for each of the three
            // primary sections of the activity.
            SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

            // Set up the ViewPager with the sections adapter.
            mViewPager = (ViewPager) findViewById(R.id.pager);
            mViewPager.setAdapter(mSectionsPagerAdapter);

            // When swiping between different sections, select the corresponding
            // tab. We can also use ActionBar.Tab#select() to do this if we have
            // a reference to the Tab.
            mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    actionBar.setSelectedNavigationItem(position);
                }
            });

            // For each of the sections in the app, add a tab to the action bar.
            for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
                // Create a tab with text corresponding to the page title defined by
                // the adapter. Also specify this Activity object, which implements
                // the TabListener interface, as the callback (listener) for when
                // this tab is selected.
                actionBar.addTab(
                        actionBar.newTab()
                                .setText(mSectionsPagerAdapter.getPageTitle(i))
                                .setTabListener(this));
            }
        }


        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            switch (id) {
                case R.id.action_menu_settings:
                    openSettings();
                    break;
                default:
                    openSettings();
                    break;
            }

            return super.onOptionsItemSelected(item);
        }

        @Override
        public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
            // When the given tab is selected, switch to the corresponding page in
            // the ViewPager.
            mViewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        }

        @Override
        public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        }

        public void openSettings() {
            startActivity(new Intent(this, SettingsActivity.class));
        }
    }

FragmentPagerAdapter

public class SectionsPagerAdapter extends FragmentPagerAdapter {
public static String FIRST_SECTION_TITLE = "Today";
public static String SECOND_SECTION_TITLE = "Week";
public static String THIRD_SECTION_TITLE = "Month";

public SectionsPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int position) {
    // getItem is called to instantiate the fragment for the given page.
    Fragment fragment;

    switch (position) {
        case 1:
            fragment = WeekFragment.newInstance(position + 1);
            break;
        case 2:
            fragment = MonthFragment.newInstance(position + 1);
            break;
        default:
            fragment = TodayFragment.newInstance(position + 1);
            break;
    }

    return fragment;
}

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

@Override
public CharSequence getPageTitle(int position) {
    Locale l = Locale.getDefault();
    switch (position) {
        case 0:
            return FIRST_SECTION_TITLE;
        case 1:
            return SECOND_SECTION_TITLE;
        case 2:
            return THIRD_SECTION_TITLE;
    }
    return null;
}

}

片段(所有3个片段都相同,只是xml布局更改)

public class MonthFragment extends Fragment {
/**
 * The fragment argument representing the section number for this
 * fragment.
 */
private static final String ARG_SECTION_NUMBER = "section_number";

/**
 * Returns a new instance of this fragment for the given section
 * number.
 */
public static MonthFragment newInstance(int sectionNumber) {
    MonthFragment fragment = new MonthFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_SECTION_NUMBER, sectionNumber);
    fragment.setArguments(args);
    return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_month, container, false);;
    return rootView;
}

}

2 个答案:

答案 0 :(得分:0)

您可以从mViewPager.getCurrentItem()获取当前位置。 另外,尝试使用FragmentStatePagerAdapter而不是FragmentPagerAdapter。

编辑:看起来每次都会返回一个新实例。 在这种情况下,您可以尝试这个

Fragment f = getFragmentManager().getFragmentById(mViewPager.getId())

答案 1 :(得分:0)

通过移动每个片段中的所有应用程序逻辑来解决问题(因为片段是一种Activity)。问题是,通过以下实现,在每个选项卡滑动更改时创建Fragment,这意味着它不会保存以前的状态。