1
I have an Activity that has 2 tabs and wanted to know how to change tab not only when clicking on one of them, but also when sliding (left and right) on the screen.
My Activity:
public class MainActivity extends Activity {
private Fragment1 frag1;
private Fragment2 frag2;
ActionBar bar;
Tab tab1;
Tab tab1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
frag1 = new Fragment1();
frag2 = new Fragment2();
tab1 = bar.newTab();
tab1.setText("Tab1");
tab1.setTabListener(new ConfigTab(frag1, R.id.frag1));
bar.addTab(tab1);
tab2 = bar.newTab();
tab2.setText("Tab2");
tab2.setTabListener(new ConfigTab(frag2, R.id.frag1));
bar.addTab(tab2);
}
}
And the configTab class:
public class ConfigTab implements TabListener {
private Fragment fragment;
private int placeholder;
public ConfigTab(Fragment fragment, int placeholder) {
this.fragment = fragment;
this.placeholder = placeholder;
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.add(placeholder, fragment);
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
}
}
Error print on mainActivity, highlighted below:
Print of the error occurred:
It’s a little long to answer your question without knowing your code. There is some work behind what you ask and that work in the form of an answer may not meet your particular case. It would be better to put the relevant code in the question to get a more targeted help to your particular case.
– Zuul
@Zuul ready posted.. the tabs then working perfectly when clicked... just wanted when sliding on the screen automatically change the tabs.
– Pedro Rangel
I added a photo in my post of the line where the error occurs...
– Pedro Rangel