我想在操作栏中使用标签。为简单起见,现在只有一个标签。问题是没有可见的视图/ ui。
创建包含标签的活动的功能 -
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tabs = new Vector<ActionBar.Tab>();
ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab accountsTab = actionbar.newTab().setText("Accounts");
Fragment accountsFragment = new AccountsFragment();
accountsTab.setTabListener(new MyTabListener(accountsFragment));
actionbar.addTab(accountsTab);
tabs.add(accountsTab);
}
扩展Fragment的片段AccountsFragment的oncreateview(android.app.Fragment):
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
TextView textView = new TextView(getActivity());
textView.setText("SimpleFragmentText");
textView.setVisibility(View.VISIBLE);
textView.setTextSize(20);
return textView;
}
最后,Tab监听器如下:
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
if(fragment!=null) {
fragmentTransaction.add(fragment,"accounts");
fragmentTransaction.show(fragment);
}
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
if(fragment!=null) {
fragmentTransaction.remove(fragment);
}
}
所有其他功能都不会被覆盖。除标题为“帐户”的标签外,没有任何内容显示。
我的main.xml包含线性布局。
答案 0 :(得分:2)
在你的onTabSelected中尝试这个 -
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = (Fragment) Fragment.instantiate(mActivity, mClass.getName());
ft.add(android.R.id.content, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
}
答案 1 :(得分:1)
试试这个:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tabs = new Vector<ActionBar.Tab>();
ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab accountsTab = actionbar.newTab().setText("Accounts");
accountsTab.setTabListener(new MyTabListener());
actionbar.addTab(accountsTab);
tabs.add(accountsTab);
}
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
if(fragment!=null) {
AccountsFragment frag = new AccountsFragment();
fragmentTransaction.add(android.R.id.content, frag);
}
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
if(fragment!=null) {
fragmentTransaction.remove(fragment);
}
}