是的,你问的都可以。
简而言之:
在您onClickListener
指定Button
使隐藏选项卡可见的情况下,您应该调用ActionBar.addTab
.
添加新的Fragment
根据包含您的布局Fragments
,您可以调用FragmentTransaction.hide
and FragmentTransaction.show
,否则我会假设您正在Fragment
动态添加,因此使用 a FragmentPagerAdapter
,在这种情况下将您的新添加Fragment
到您的List
.
链接
操作栏- addTab
FragmentTransaction -隐藏,显示
您还应该阅读添加片段文档。
这是一个非常基本的示例:
ViewPager 的适配器
public class PagerAdapter extends FragmentPagerAdapter {
/**
* The list of {@link Fragment}s used in the adapter
*/
private final List<Fragment> mFragments = new ArrayList<Fragment>();
/**
* Constructor for <code>PagerAdapter</code>
*
* @param fm The {@link FragmentManager} to use.
*/
public PagerAdapter(FragmentManager fm) {
super(fm);
}
/**
* Adds a new {@link Fragment} to the adapter
*
* @param fragment The new {@link Fragment} to add to the list
*/
public void addFragment(Fragment fragment) {
mFragments.add(fragment);
notifyDataSetChanged();
}
/**
* {@inheritDoc}
*/
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
/**
* {@inheritDoc}
*/
@Override
public int getCount() {
return mFragments.size();
}
}
虚拟碎片
public static final class DummyFragment extends Fragment implements View.OnClickListener {
/**
* Empty constructor as per the {@link Fragment} docs
*/
public DummyFragment() {
}
/**
* @param color The color to make the root view
* @return A new instance of {@link DummyFragment}
*/
public static DummyFragment getInstance(int color) {
final Bundle bundle = new Bundle();
bundle.putInt("color", color);
final DummyFragment fragment = new DummyFragment();
fragment.setArguments(bundle);
return fragment;
}
/**
* {@inheritDoc}
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
rootView.setBackgroundColor(getArguments().getInt("color"));
return rootView;
}
/**
* {@inheritDoc}
*/
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// This should be your Button
view.setOnClickListener(this);
}
/**
* {@inheritDoc}
*/
@Override
public void onClick(View v) {
// This adds the new tab
((MainActivity) getActivity()).addTab(2, Color.BLUE);
}
}
调用添加每个 Fragment
/**
* Used to add a new {@link Fragment} to {@link ViewPager}'s adapter and
* adds a new {@link Tab} to the {@link ActionBar}.
*
* @param pageTitle The title of the tab
* @param color The background color of the {@link Fragment}
*/
public void addTab(int pageTitle, int color) {
mPagerAdapter.addFragment(DummyFragment.getInstance(color));
mActionBar.addTab(mActionBar.newTab()
.setText("" + pageTitle)
.setTabListener(this));
}