I am using the AppCompat library for my android app. I am trying to add Action Bar Tab that I have done now I could not add the fragment on click on ActionBar Tabs
. Here in below code, there I have two tabs on click on them I want to inflate the fragment
Any idea for this ??
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) {
}
}
First, import this TabListener to your project instead of implementing ActionBar.TabListener
in your Activity. Then in your layout activity_main
make sure you have a fragment container like so
<LinearLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
Then it's easy, add tabs to your actionbar like this:
Tab tab1 = actionBar
.newTab()
...
.setTabListener(new SupportFragmentTabListener<CustomFragment>(R.id.container, this,
"first", CustomFragment.class));
If you want to learn more, ie how to style your tabs check here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.