I am trying to attach ActionBar Tabs to respect fragment, But it is not working. I don't no where i am getting wrong.
Here is my FragmentActivity
public class MainActivity extends FragmentActivity implements TabListener {
String cPlusPlusFrag = "CPP", javaFrag = "Java";
CPlusPlusFragment cPlusPlusFragment;
JavaFragment javaFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar mAction = getActionBar();
mAction.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
createTab(mAction, cPlusPlusFrag);
createTab(mAction, javaFrag);
}
public void createTab(ActionBar mActionBar, String tabName) {
Tab tab = mActionBar.newTab();
tab.setText(tabName);
tab.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);
return true;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(this, tab.getText() + "Re-Selected", Toast.LENGTH_LONG)
.show();
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (cPlusPlusFrag.equals(tab.getText())) {
if (cPlusPlusFragment == null) {
cPlusPlusFragment = new CPlusPlusFragment();
ft.add(android.R.id.content, cPlusPlusFragment);
}
} else if (javaFrag.equals(tab.getText())) {
if (javaFragment == null) {
javaFragment = new JavaFragment();
ft.add(android.R.id.content, javaFragment);
}
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(this, tab.getText() + " Un-Selected", Toast.LENGTH_LONG)
.show();
if (cPlusPlusFrag.equals(tab.getText().toString())) {
ft.detach(cPlusPlusFragment);
} else if (javaFrag.equals(tab.getText().toString())) {
ft.detach(javaFragment);
}
}
}
Java Fragment code.
public class JavaFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View viewToInflate = inflater.inflate(R.layout.java_frag_layout,
container);
return viewToInflate;
};
}
C++ Fragment code.
public class CPlusPlusFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View viewToInflate = inflater.inflate(R.layout.cplusplus_frag_layout,
container);
return viewToInflate;
}
}
The Problem is in
methods: onTabSelected, onTabUnSelected
and variables: cPlusPlusFragment and javaFrag (You did not Declared/Created them anywhere)
*Solution*
// The following variables are at Class level (data members)
String cPlusPlusFragment = "C++";
String javaFrag = "Java"
// Pass them in the method createTab accordingly
createTab(mActionBar, cPlusPlusFragment);
createTab(mActionBar, javaFrag);
// Modify you onTabSelected and onTabUnselected methods as follows:
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (cPlusPlusFrag.equals(tab.getText().toString)) {
if (cPlusPlusFragment == null) {
cPlusPlusFragment = new CPlusPlusFragment();
// No need to Create custom FragmentTransaction, use
// one that is passed in the argument
ft.add(android.R.id.content, cPlusPlusFragment);
} else {
ft.attach(cPlusPlusFragment);
}
} else if (javaFrag.equals(tab.getText().toString)) {
if (javaFragment == null) {
javaFragment = new JavaFragment();
ft.add(android.R.id.content, javaFragment);
} else {
ft.attach(javaFragment);
}
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(this, tab.getText() + " Un-Selected", Toast.LENGTH_LONG)
.show();
if (cPlusPlusFrag.equals(tab.getText().toString)) {
ft.detach(cPlusPlusFragment);
} else if (javaFrag.equals(tab.getText().toString)) {
ft.detach(javaFragment);
}
}
I am 100 % sure that this will solve your problem :)
I see nothing wrong in you code at first sight apart from the fact that you are not commiting your fragment changes.
EveryTime you call to getFragmentManager().beginTransaction(). you have to call .commit() at the end of the line like this:
getFragmentManager().beginTransaction().replace(R.id.main_layout, javaFragment).commit();
Hope it helps :)
Related
I have a main activity which contains the action bar with 3 menu buttons in it.
I then have a fragment within this main activity which has a list.
I would like to be able to refresh the list in the fragment from the main activity, when one of the menu buttons is clicked, or preferably just removed all the rows from the list.
Any help is appreciated.
Thanks.
public class Favourite extends SherlockFragmentActivity {
ActionBar actionBar;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favourite);
actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(R.drawable.actionbar_bg);
bg.setTileModeX(TileMode.REPEAT);
getSupportActionBar().setBackgroundDrawable(bg);
getSupportActionBar().setIcon(R.drawable.favourite_title);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tabAll = actionBar.newTab();
ActionBar.Tab tabfavs = actionBar.newTab();
ActionBar.Tab tabhist = actionBar.newTab();
tabAll.setText("all");
tabfavs.setText("favs");
tabhist.setText("hist");
tabAll.setTabListener(new MyTabListener());
tabfavs.setTabListener(new MyTabListener());
tabhist.setTabListener(new MyTabListener());
actionBar.addTab(tabAll);
actionBar.addTab(tabfavs);
actionBar.addTab(tabhist);
try{
}
catch(Exception e)
{
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.actionbar_itemlist_favourite, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.history:
break;
case R.id.favourite:
Intent favAct = new Intent(this, Favourite.class);
startActivity(favAct);
break;
case R.id.delete:
///I WANT TO BE ABLE TO REFRESH FRAGMENTLIST FROM HERE
}
return true;
}
}
class MyTabListener implements ActionBar.TabListener {
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if(tab.getPosition()==0)
{
FavouriteAllWords frag = new FavouriteAllWords();
ft.replace(android.R.id.content, frag);
}
else if(tab.getPosition()==1)
{
FavouriteFavWords frag = new FavouriteFavWords();
ft.replace(android.R.id.content, frag);
}
else if(tab.getPosition()==2)
{
FavouriteHistWords frag = new FavouriteHistWords();
ft.replace(android.R.id.content, frag);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
////////////////////MY LIST FRAGMENT CLASS
public class FavouriteAllWords extends ListFragment {
ArrayAdapter<String> adapter;
List<String> stringOfFavWords;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle saved)
{
adapter = new ArrayAdapter<String>(
inflater.getContext(), R.layout.row, stringOfFavWords);
setListAdapter(adapter);
return super.onCreateView(inflater, group, saved);
}
#Override
public void onActivityCreated (Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
}
You can easily achieve this using INTERFACE
MainActivity.java
public class MainActivity extends Activity {
public FragmentRefreshListener getFragmentRefreshListener() {
return fragmentRefreshListener;
}
public void setFragmentRefreshListener(FragmentRefreshListener fragmentRefreshListener) {
this.fragmentRefreshListener = fragmentRefreshListener;
}
private FragmentRefreshListener fragmentRefreshListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button)findViewById(R.id.btnRefreshFragment);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(getFragmentRefreshListener()!=null){
getFragmentRefreshListener().onRefresh();
}
}
});
}
public interface FragmentRefreshListener{
void onRefresh();
}
}
MyFragment.java
public class MyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = null; // some view
/// Your Code
((MainActivity)getActivity()).setFragmentRefreshListener(new MainActivity.FragmentRefreshListener() {
#Override
public void onRefresh() {
// Refresh Your Fragment
}
});
return v;
}
}
Just make your update/refresh method public and call it from your Activity.
OR
Use LocalBroadcastManager or EventBus to send event from your Activity, and by subscribing to this event in a Fragment - react to it and call refresh/update method.
Your activity can call methods in the fragment by acquiring a reference to the Fragment.
(1) Provide a tag when you add your fragment.
transaction.add(R.id.fragment_container, myFragment, "myfragmentTag");
(2) In your hosting activity you can find the fragment and have access to it's methods.
FragmentManager fm = getSupportFragmentManager();
myFragment f = (myFragment) fm.findFragmentByTag("myfragmentTag");
f.refreshAdapter()
(3) refreshAdapter() could now call adapter.notifyDataSetChanged().
This is one of the recommended ways to communicate up to a fragment.
The interface implementation is mainly for communicating back to the activity.
Biraj Zalavadia's answer is 100% right, you will call nay fragment methods from using interface....
this interface methods is running without error...
use this in MainActivity above oncreate
private FragmentRefreshListener fragmentRefreshListener;
public FragmentRefreshListener getFragmentRefreshListener() {
return fragmentRefreshListener;
}
public void setFragmentRefreshListener(
FragmentRefreshListener fragmentRefreshListener) {
this.fragmentRefreshListener = fragmentRefreshListener;
}
inside of Activity
private void refreshcall(String result2) {
// TODO Auto-generated method stub
if (getFragmentRefreshListener() != null) {
getFragmentRefreshListener().onRefresh(result2);
}
}
and put this in needed Fragment
private FragmentRefreshListener fragmentRefreshListener;
public FragmentRefreshListener getFragmentRefreshListener() {
return fragmentRefreshListener;
}
public void setFragmentRefreshListener(
FragmentRefreshListener fragmentRefreshListener) {
this.fragmentRefreshListener = fragmentRefreshListener;
}
Communicating with Other Fragments
http://developer.android.com/training/basics/fragments/communicating.html
This can also be used to communicate between an Activity and a Fragment.
When you click on ActionBar any Button then call interface to refresh the ListFragment. Because in java interface is used for inter-communication.
In Kotlin
Get the list of Support Fragment from the activity and check Instance and then call fragment function
val fragments = supportFragmentManager.fragments
for (fragment in fragments) {
if (fragment is HomeCategoriesFragment) {
fragment.updateAdapter() // Define function in Fragment
}
}
Dears,
I searched for this issue for more than a day but with no luck.
I implement exactly the code posted here:
Adding Navigation Tabs
My code for onTabSelected look like:
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.instantiate(mActivity, mClass.getName());
ft.add(R.id.alert_fragment_container, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
// prepare adapter for ExpandableListView
Log.i("After Adapter Created", "Passed");
final ExpandableListAdapter expListAdapter = new AlertsAdapter(
mActivity, myAlerts, violations);
Log.i("After Adapter Initialized", "Passed");
((MyCustomFragment)mFragment).violations.setAdapter(expListAdapter);
}
The code is working fine till last line, where I need to set the adapter for public static list initialized in MyCustomFragment in onCreateView, here my code for fragment:
public class MyCustomFragment extends Fragment {
public MyCustomFragment() {
}
public static ExpandableListView violations;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_alerts_poi, container, false);
violations = (ExpandableListView) rootView.findViewById(R.id.POIAlertList);
Log.i("onCreateView POI", "Called");
return rootView;
}
}
It give Null pointer error. With my debugging logs, I notice that this log Log.i("onCreateView POI", "Called"); appears after this Log.i("After Adapter Initialized", "Passed");. This means that I'm trying to set the adapter for a fragment isn't initialized yet.
This is the exact problem I'm face, I need to fed the ExpandableListView with data based on Tab selection in onTabSelected.
What I'm doing wrong? What is the best solution?
Regards,
It seems that you need a ViewPager, I just implemented a navigation tabs few days ago, here is my code, it navigates between 4 fragments:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener{
private ActionBar actionBar;
private ViewPager mViewPager;
private AppSectionsPagerAdapter mAppSectionsPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
actionBar=getActionBar();
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
actionBar.addTab(actionBar.newTab().setIcon(R.drawable.icon1).setTabListener(this));
actionBar.addTab(actionBar.newTab().setIcon(R.drawable.icon2).setTabListener(this));
actionBar.addTab(actionBar.newTab().setIcon(R.drawable.icon3).setTabListener(this));
actionBar.addTab(actionBar.newTab().setIcon(R.drawable.icon4).setTabListener(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.action_menu, menu);
return true;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
And here is the adapter:
public class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return new Fragment1();
case 1:
return new Fragment2();
case 2:
return new Fragment3();
case 3:
return new Fragment4();
}
return null;
}
#Override
public int getCount() {
return 4;
}
}
Have a look # this Tablayout.onTabselected for latest API updates. ActionBar.TabListener is a old implementation.
Yesterday I downloaded new HoloEverywhere library.
Currently, I have problem with tab navigation after screen rotation.
My Home Activity:
public class MainActivity extends Activity implements TabListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setUpTabs();
}
private void setUpTabs() {
String[] titles = {
"First", "Second",
};
ActionBar supportActionBar = getSupportActionBar();
for (int i = 0; i < titles.length; i++) {
ActionBar.Tab tab = supportActionBar.newTab();
tab.setText(titles[i]);
tab.setTag(MyFragment.TAG);
tab.setTabListener(this);
supportActionBar.addTab(tab, false);
}
supportActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
supportActionBar.setSelectedNavigationItem(0);
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction fragmentTransaction) {
final String fragmentTag = tab.getTag().toString();
Fragment fragment = getSupportFragmentManager().findFragmentByTag(fragmentTag);
if (fragment == null) {
fragment = new MyFragment();
fragmentTransaction.add(android.R.id.content, fragment, fragmentTag);
} else {
fragmentTransaction.attach(fragment);
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction fragmentTransaction) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag((String) tab.getTag());
if (fragment != null) {
fragmentTransaction.detach(fragment);
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction fragmentTransaction) {
}
}
And my Fragment class.
public class MyFragment extends Fragment {
public static final String TAG = MyFragment.class.getCanonicalName();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = new View(getActivity());
view.setBackgroundColor(Color.BLACK);
return view;
}
}
When I rotate the screen fragment not displaying. It displays when i select tab (which is not currently selected) manually.
I just solve the problem.
I post my code here and see if those can help you :D
if (savedInstanceState == null){
TabHomeFragment homeFragment = new TabHomeFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, homeFragment, "home_fragment").commit();
}else{
TabHomeFragment homeFragment = (TabHomeFragment) getSupportFragmentManager().findFragmentByTag("home_fragment");
}
Those code are located in OnCreate method.
When the Device rotate and Ortiention change, the fragment will recreate again. So add a if clase to check if there is already one here.
But I am using normal Fragment in Android. Hope it can help you a little.
I'm having a difficulty to show a fragment in a container when a menu item is clicked.Below is my code.
I tried to do ft.show(); inside onMenuItemClick of Login Menu Item but its not working and I don't know what am I doing wrong as I'm neither getting any errors nor the app is crashing. Fragments which are attached to the Tabs are working and displaying just fine. It's just that when I try to load a fragment in an container when menu item is clicked at that time nothing happens.Please point me in a right direction and lemme know what am I doing wrong.
public class HomeActivity extends SherlockFragmentActivity {
public SherlockFragment fragment;
FragmentTransaction ft;
public static Context appContext;
ActionBar actionbar;
String mCurFilter;
LoginScreenFragment loginFragment;
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
appContext = getApplicationContext();
actionbar = getSupportActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab HomeTab = actionbar.newTab().setText("Home");
ActionBar.Tab CartTab = actionbar.newTab().setText("Cart");
ActionBar.Tab myTab = actionbar.newTab().setText("MyFragment");
ActionBar.Tab moreTab = actionbar.newTab().setText("More...");
HomeFragment homeFragment = new HomeFragment();
CartFragment cartFragment = new CartFragment();
MyFragment myFragment = new MyFragment();
MoreFragment moreFragment = new MoreFragment();
loginFragment = new LoginScreenFragment();
HomeTab.setTabListener(new MyTabsListener(homeFragment));
CartTab.setTabListener(new MyTabsListener(cartFragment));
myTab.setTabListener(new MyTabsListener(myFragment));
moreTab.setTabListener(new MyTabsListener(moreFragment));
actionbar.addTab(HomeTab);
actionbar.addTab(CartTab);
actionbar.addTab(myTab);
actionbar.addTab(moreTab);
ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.fragment_container, homeFragment);
ft.show(homeFragment);
ft.add(R.id.fragment_container, cartFragment);
ft.hide(cartFragment);
ft.add(R.id.fragment_container, myFragment);
ft.hide(myFragment);
ft.add(R.id.fragment_container, moreFragment);
ft.hide(moreFragment);
ft.add(R.id.fragment_container, loginFragment);
ft.hide(loginFragment);
ft.commit();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getSupportActionBar()
.getSelectedNavigationIndex());
System.out.println("onSaveInstanceState");
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
MenuItem item = menu.add("Search");
item.setIcon(android.R.drawable.ic_menu_search);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
View searchView = SearchViewCompat.newSearchView(this);
if (searchView != null) {
SearchViewCompat.setOnQueryTextListener(searchView,
new OnQueryTextListenerCompat() {
#Override
public boolean onQueryTextChange(String newText) {
mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
return true;
}
});
item.setActionView(searchView);
}
MenuItem loginItem = menu.add("Login");
loginItem.setTitle("Login");
loginItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
loginItem.setOnMenuItemClickListener(new OnMenuItemClickListener(){
#Override
public boolean onMenuItemClick(MenuItem item) {
//I wanted to show "loginFragment" when the Login button is clicked.But unfortunately its not showing up.Also the application is not giving any errors or crashing
ft.show(loginFragment);
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.menuitem_home) {
Toast.makeText(appContext, "Home", Toast.LENGTH_SHORT).show();
return true;
} else if (itemId == R.id.menuitem_shop) {
Toast.makeText(appContext, "Shop", Toast.LENGTH_SHORT).show();
return true;
} else if (itemId == R.id.menuitem_cart) {
Toast.makeText(appContext, "Cart", Toast.LENGTH_SHORT).show();
return true;
} else if (itemId == R.id.menuitem_my) {
Toast.makeText(appContext, "My", Toast.LENGTH_SHORT).show();
return true;
} else if (itemId == R.id.menuitem_more) {
Toast.makeText(appContext, "More...", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
static class MyTabsListener implements ActionBar.TabListener {
public SherlockFragment fragment;
public MyTabsListener(SherlockFragment fragment) {
this.fragment = fragment;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
System.out.println("TabReselected " + tab.getPosition());
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
System.out.println("TabSelected " + tab.getPosition());
ft.show(this.fragment);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
System.out.println("TabUnselected " + tab.getPosition());
ft.hide(this.fragment);
}
}
}
Instead of adding the fragments to one container and hiding & showing them you can try replacing fragments when you click on your menu buttons.
for ex- when you click on login button
ft.replace(R.id.fragment_container, loginFragment).commit();
give it a try hope it will work.
You should begin and commit the transaction again. Try:
#Override
public boolean onMenuItemClick(MenuItem item) {
ft = getSupportFragmentManager().beginTransaction();
ft.show(loginFragment);
ft.commit();
return false;
}
I've just set up a project using tabs + actionbarsherlock + fragments, and want to make sure my approach is correct before moving on - mainly the use of my onTabSelected calling newInstance, this example is derived from CommonsWare's https://github.com/commonsguy/cw-omnibus/tree/master/ActionBar/TabFragmentDemo sample code.
My TabFragmentActivity:
public class TabFragmentActivity extends SherlockFragmentActivity
implements TabListener {
private static final String KEY_POSITION="position";
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
ActionBar bar=getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
bar.addTab(bar.newTab().setText(R.string.tab1)
.setTabListener(this).setTag(0));
bar.addTab(bar.newTab().setText(R.string.tab2)
.setTabListener(this).setTag(1));
bar.addTab(bar.newTab().setText(R.string.tab3)
.setTabListener(this).setTag(2));
bar.addTab(bar.newTab().setText(R.string.tab4)
.setTabListener(this).setTag(3));
if (state != null) {
bar.setSelectedNavigationItem(state.getInt(KEY_POSITION));
}
}
#Override
public void onSaveInstanceState(Bundle state) {
state.putInt(KEY_POSITION,
getSupportActionBar().getSelectedNavigationIndex());
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
int i=((Integer)tab.getTag()).intValue();
if (i == 0){
ft.replace(android.R.id.content,
Tab1Fragment.newInstance(i));
}
else if (i == 1){
ft.replace(android.R.id.content,
Tab2Fragment.newInstance(i));
}
else if (i == 2){
ft.replace(android.R.id.content,
Tab3Fragment.newInstance(i));
}
else if (i == 3){
ft.replace(android.R.id.content,
Tab4Fragment.newInstance(i));
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
My Tab1Fragment:
public class Tab1Fragment extends SherlockFragment {
private static final String KEY_POSITION="position";
static Tab1Fragment newInstance(int position) {
Tab1Fragment frag=new Tab1Fragment();
Bundle args=new Bundle();
args.putInt(KEY_POSITION, position);
frag.setArguments(args);
return(frag);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View result=inflater.inflate(R.layout.tab1, container, false);
return(result);
}
}
Where my Tab1Fragment will eventually do a lot of AsyncTask heavy loading - is this ok as well?