我正在为我的Android应用程序使用AppCompat库。我正在尝试添加我现在已经完成的Action Bar选项卡我无法在点击ActionBar Tabs
时添加片段。在下面的代码中,我有两个选项卡点击它们我想要膨胀片段
对此有任何想法吗?
MainActivity.java
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
private SearchView mSearchView;
private ActionBar mActionBar;
private Fragment mFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mActionBar = getSupportActionBar();
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// create first tab
ActionBar.Tab tab = mActionBar.newTab().setText("Free apps")
.setTabListener(this);
mActionBar.addTab(tab);
// create second tab
tab = mActionBar.newTab().setText("Paid apps")
.setTabListener(this);
mActionBar.addTab(tab);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
MenuItem searchItem = menu.findItem(R.id.action_bar_search);
mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_bar_search:
mSearchView.setIconified(false);
return true;
}
return false;
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
if (tab.getPosition() == 0) {
// first tab
} else {
// second tab
}
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
}
答案 0 :(得分:0)
首先,将this TabListener导入您的项目,而不是在您的Activity中实施ActionBar.TabListener
。然后在你的布局activity_main
中确保你有一个像这样的片段容器
<LinearLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
然后很简单,在操作栏上添加标签,如下所示:
Tab tab1 = actionBar
.newTab()
...
.setTabListener(new SupportFragmentTabListener<CustomFragment>(R.id.container, this,
"first", CustomFragment.class));
如果您想了解更多信息,例如如何设置标签样式,请检查here