EDIT cjohn caught the missing piece. I was forgetting to call init() on my YTPlayerFragment.
New to android dev. I am trying to put a youtube video inside a YouTubePlayerFragment which is nested inside another fragment. Logcat doesn't show any errors, but my player fragment only shows a black box. Placing log statements inside my OnInitializedListener, it seems it's not even being called.
The ContentFragment that contains the YouTubePlayerFragment is a tab inside a ViewPager. My code is below. MainActivity ContentFragment, ContentFragment contains the YouTubePlayerFragment.
MainActivity.java:
public class MainActivity extends FragmentActivity{
TabsPagerAdapter mAdapter;
ViewPager mViewPager;
Boolean mLoggedIn;
String[] mTabs = {"Library", "Content", "Quotes"};
#Override
protected void onCreate(Bundle savedInstanceState) {
final ActionBar actionBar = getActionBar();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.viewPager);
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
mViewPager.setAdapter(mAdapter);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
};
for (String tab : mTabs) {
actionBar.addTab(actionBar.newTab().setText(tab).setTabListener(tabListener));
}
}
}
TabsPagerAdapter.java:
public class TabsPagerAdapter extends FragmentPagerAdapter{
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
return new LibraryFragment();
case 1:
return new ContentFragment();
case 2:
return new QuotesFragment();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
ContentFragment.java:
public class ContentFragment extends Fragment {
public ContentFragment() {
// Required empty public constructor
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setRetainInstance(true);
View v = inflater.inflate(R.layout.fragment_content, container, false);
YTPlayerFragment video = YTPlayerFragment.newInstance("nCgQDjiotG0");
getFragmentManager().beginTransaction().replace(R.id.youtubeFragment, video).commit();
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
YTPlayerFragment.java:
public class YTPlayerFragment extends YouTubePlayerSupportFragment {
private YouTubePlayer activePlayer;
private final static String DEV_KEY = "KEY";
public static YTPlayerFragment newInstance(String url) {
YTPlayerFragment player = new YTPlayerFragment();
Bundle bundle = new Bundle();
bundle.putString("url", url);
player.setArguments(bundle);
return player;
}
private void init() {
initialize(DEV_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
activePlayer = youTubePlayer;
Log.d("YOUTUBE", "Successfully initialized");
activePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
if (!b) {
activePlayer.cueVideo(getArguments().getString("url"));
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Log.e("YOUTUBE", youTubeInitializationResult.toString());
}
});
}
}
fragment_content.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="2dp"
android:clipToPadding="false"
android:scrollbarStyle="outsideOverlay"
android:orientation="vertical" >
<FrameLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/youtubeFragment" />
</LinearLayout>
Inside your ContentFragment, you're trying to add another Fragment as a child. To do this, you require the child fragment manager, acquired by calling getChildFragmentManager():
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setRetainInstance(true);
View v = inflater.inflate(R.layout.fragment_content, container, false);
YTPlayerFragment video = YTPlayerFragment.newInstance("nCgQDjiotG0");
getChildFragmentManager().beginTransaction().replace(R.id.youtubeFragment, video).commit();
return v;
}
Related
I am trying to display news of different categories under different tabs using TabLayout. The corresponding fragments do not load at all, only the tabs are displayed. The app freezes when I try to scroll or select a tab such that even the tabIndicator barely moves to the corresponding tab and Android displays "Not responding" message.
MainActivity.java
public class MainActivity extends AppCompatActivity{
Toolbar toolbar;
TabLayout tabLayout;
ViewPager2 viewPager2;
NewsPagerAdapter newsPagerAdapter;
TabLayoutMediator tabLayoutMediator;
String[] tabTitles = new String[]{"HOME","BUSINESS","HEALTH","TECHNOLOGY","SPORTS"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.tbCustom);
tabLayout = findViewById(R.id.tlCategories); setSupportActionBar(toolbar);
viewPager2 = findViewById(R.id.vpNews);
newsPagerAdapter = new NewsPagerAdapter(getSupportFragmentManager(),getLifecycle());
viewPager2.setAdapter(newsPagerAdapter);
tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPager2, (tab, position) -> tab.setText(tabTitles[position]));
tabLayoutMediator.attach();
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager2.setCurrentItem(tab.getPosition());
newsPagerAdapter.notifyDataSetChanged();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
tabLayout.selectTab(tabLayout.getTabAt(position));
}
#Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
tabLayoutMediator.detach();
viewPager2.setAdapter(null);
}
}
NewsPagerAdapter.java
public class NewsPagerAdapter extends FragmentStateAdapter {
public NewsPagerAdapter(#NonNull FragmentManager fragmentManager, #NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position)
{
case 0: return new HomeFragment();
case 1: return new BusinessFragment();
case 2: return new HealthFragment();
case 3: return new TechnologyFragment();
case 4: return new SportsFragment();
default: return null;
}
}
#Override
public int getItemCount() {
return 5;
}
}
Home Fragment.java - Other fragments have the same structure
public class HomeFragment extends Fragment {
#Override
public void onDestroyView() {
super.onDestroyView();
recyclerView.setAdapter(null);
}
#Override
public void onDetach() {
super.onDetach();
}
private List<NewsModelClass> homeNews = new ArrayList<>();
String country = "in";
String category = "general";
int pageSize = 50;
private RecyclerView recyclerView;
NewsAdapter newsAdapter;
final String API_KEY = "ba88d060a3e049ca9fa46f2bea0d52c4";
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = v.findViewById(R.id.rvHome);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
return v;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
newsAdapter = new NewsAdapter(getContext(),homeNews);
recyclerView.setAdapter(newsAdapter);
fetchNews();
}
private void fetchNews()
{
Call<NewsArticles> call = RetrofitClient.getInstance().getMyApi().getNews(country,pageSize,category,API_KEY);
call.enqueue(new Callback<NewsArticles>() {
#Override
public void onResponse(#NonNull Call<NewsArticles> call, #NonNull Response<NewsArticles> response) {
if(response.isSuccessful()) {
if (!homeNews.isEmpty()) {
homeNews.clear();
}
homeNews=response.body().getArticles();
newsAdapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(#NonNull Call<NewsArticles> call, Throwable t) {
Toast.makeText(getContext(),"Something is wrong",Toast.LENGTH_SHORT).show();
}
});
}
}
fragment_home.xml - Other fragments have the same layout
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.HomeFragment">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rvHome"
android:fitsSystemWindows="true"
android:padding="8dp"/>
</FrameLayout>
NewsAdapter.java
public class NewsAdapter extends
RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
Context context;
List<NewsModelClass> allNews;
public NewsAdapter(Context context,List<NewsModelClass>
allNews) {
this.context = context;
this.allNews = allNews;
}
#NonNull
#Override
public NewsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View newsItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_news, parent, false);
return new NewsViewHolder(newsItem);
}
#Override
public void onBindViewHolder(#NonNull NewsViewHolder holder, int position) {
NewsModelClass currentNewsItem = allNews.get(position);
holder.title.setText(currentNewsItem.getTitle());
holder.author.setText(currentNewsItem.getAuthor());
if (currentNewsItem.getUrlToImage() != null)
Glide.with(holder.itemView.getContext()).load(Uri.parse(currentNewsItem.getUrlToImage())).into(holder.articleImage);
holder.cardView.setOnClickListener(v -> {
String newsUrl = currentNewsItem.getUrl();
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
int colorInt = Color.parseColor("#F1ECC3");
CustomTabColorSchemeParams defaultColors = new CustomTabColorSchemeParams.Builder()
.setToolbarColor(colorInt)
.build();
builder.setDefaultColorSchemeParams(defaultColors);
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(context, Uri.parse(newsUrl));
});
}
#Override
public int getItemCount() {
return allNews.size();
}
public static class NewsViewHolder extends RecyclerView.ViewHolder {
ImageView articleImage;
TextView title, author;
CardView cardView;
public NewsViewHolder(#NonNull View itemView) {
super(itemView);
articleImage = itemView.findViewById(R.id.ivArticleImage);
title = itemView.findViewById(R.id.tvHeadline);
author = itemView.findViewById(R.id.tvAuthor);
cardView = itemView.findViewById(R.id.cardView);
}
}
}
I have tried to add a fragment inside another fragment inside viewpager using getChildFragmentManager(). I got following error,
java.lang.IllegalStateException: Activity has been destroyed
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1549)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:654)
at android.support.v4.app.BackStackRecord.commitAllowingStateLoss(BackStackRecord.java:625)
at com.lakeba.gameon.userprofile.UserProfileContainerFragment.replaceFragment(UserProfileContainerFragment.java:72)
And I tried this workaround but still getting same error.
UserProfileContainerFragment.java
public class UserProfileContainerFragment extends CustomFragment {
private View rootView;
private Fragment fragment1;
public UserProfileContainerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
public static UserProfileContainerFragment newInstance() {
UserProfileContainerFragment fragment = new UserProfileContainerFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_user_profile_container, container, false);
if(savedInstanceState == null) {
UserProfileFragment userProfileFragment = UserProfileFragment.newInstance();
getChildFragmentManager().beginTransaction()
.replace(R.id.user_profile_container, userProfileFragment)
.commitAllowingStateLoss();
}
return rootView;
}
/*#Override
public void onSaveInstanceState(Bundle outState) {
//super.onSaveInstanceState(outState);
}*/
public void replaceFragment(Fragment fragment, boolean addToBackStack){
fragment1 = fragment;
if(addToBackStack){
/*getChildFragmentManager().beginTransaction()
.replace(R.id.user_profile_container, fragment)
.addToBackStack(null)
.commit();*/
getChildFragmentManager().beginTransaction()
.replace(R.id.user_profile_container, fragment)
.addToBackStack(null)
.commit();
//.commitAllowingStateLoss();
}
else{
getChildFragmentManager().beginTransaction()
.replace(R.id.user_profile_container, fragment)
.commit();
//.commitAllowingStateLoss();
}
}
#Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
HomeMapActivity.java
public class HomeMapActivity extends AppCompatActivity implements UserProfileFragment.OnUserProfileFragmentListener{
private Toolbar homeToolbar;
private ViewPager homeViewPager;
private TabLayout homeTabLayout;
private UserProfileContainerFragment userProfileContainerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_map);
/*homeToolbar = (Toolbar) findViewById(R.id.home_toolbar);
setSupportActionBar(homeToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);*/
homeViewPager = (ViewPager) findViewById(R.id.home_view_pager);
HomeViewPagerAdapter homeViewPagerAdapter = new HomeViewPagerAdapter(getSupportFragmentManager());
userProfileContainerFragment = new UserProfileContainerFragment();
homeViewPagerAdapter.addFragment(new UserProfileContainerFragment(),"Profile");
homeViewPager.setAdapter(homeViewPagerAdapter);
homeTabLayout = (TabLayout) findViewById(R.id.home_tabs);
homeTabLayout.setupWithViewPager(homeViewPager);
setTabIcons(homeTabLayout);
homeTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int tabPosition = tab.getPosition();
tab.setIcon(tabIconsArrayActivated[tabPosition]);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
int tabPosition = tab.getPosition();
tab.setIcon(tabIconsArray[tabPosition]);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
int tabPosition = tab.getPosition();
tab.setIcon(tabIconsArrayActivated[tabPosition]);
}
});
homeTabLayout.getTabAt(1).select();
}
private void setTabIcons(TabLayout homeTabLayout) {
homeTabLayout.getTabAt(0).setIcon(tabIconsArray[0]);
homeTabLayout.getTabAt(1).setIcon(tabIconsArray[1]);
homeTabLayout.getTabAt(2).setIcon(tabIconsArray[2]);
homeTabLayout.getTabAt(3).setIcon(tabIconsArray[3]);
}
#Override
public void onUserProfileEditButtonClicked() {
userProfileContainerFragment.replaceFragment(EditUserProfileFragment.newInstance(),true);
}
private class HomeViewPagerAdapter extends FragmentStatePagerAdapter{
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public HomeViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
//return mFragmentTitleList.get(position);
return null;
}
public void addFragment(Fragment fragment,String title){
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
}
}
If you look at the code in your onCreate() method you'll see the lines:
userProfileContainerFragment = new UserProfileContainerFragment();
homeViewPagerAdapter.addFragment(new UserProfileContainerFragment(),"Profile");
You first initialize the userprofileContainerFragment field with a new instance of UserProfileContainerFragment and then right below you create a new instance of UserProfileContainerFragment to be used in the ViewPager(you can easily observe this by placing a log statement in the constructor of UserProfileContainerFragment...you'll see two instances being created). Later in your code you try to use the field userProfileContainerFragment which will lead to a failure as that instance of UserProfileContainerFragment is not attached to the activity at all(this isn't the fragment used by the ViewPager).
Your code should look like below, to maintain the proper reference and not create detached fragments:
userProfileContainerFragment = new UserProfileContainerFragment();
homeViewPagerAdapter.addFragment(userProfileContainerFragment,"Profile");
I have viewpager with 3 fragments (same layout - some EditText and Buttons) and I want to dynamically add small fragment above the viewpager fragment, write something in and then hide it.
This is what I tried:
MainActivity.java:
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return MainFragment.newInstance("1");
case 1: return MainFragment.newInstance("2");
case 2: return MainFragment.newInstance("3");
default: return MainFragment.newInstance("");
}
}
#Override
public int getCount() {
return 3;
}
}
}
MainFragment.java:
public class MainFragment extends android.support.v4.app.Fragment {
EditText contentEdit;
String content, ID;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ID = getArguments().getString("msg");
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
contentEdit = (EditText) view.findViewById(R.id.editText);
contentEdit.setOnTouchListener(new OnSwipeTouchListener(getActivity()) {
public void onSwipeBottom() {
final ViewGroup newView = (ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.fragment_title, container, false);
newView.findViewById(R.id.delete_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
container.removeView(newView);
}
});
container.addView(newView, 0);
}
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
});
return view;
}
}
Try to put a frame layout above that viewPager layout BUT set it's visibility to GONE therefore it won't "exist". Now in your pager onItemClick listener for that small fragment you want to show call findViewByID(R.id.YourFrameLayout).setVisibility(View.VISIBLE); and when you want to hide it, well you get the idea. Don't forget to add your fragment to that container, e.g. YourFrameLayout
I have added 3 tabs as following.There is a spinner(drop down list) in “IntroductionFragment”.i want to change the layout of “RequirementFragment” programmatically according to the selection of spinner item in “IntroductionFragment”.Please help me
HomeLoanTabMainActivity.java
public class HomeLoanTabMainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Introduction", "Requirement", "Best offer" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_main_activity);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
TabsPagerAdapter.java
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new IntroductionFragment();
case 1:
return new RequirementFragment();
case 2:
return new BestOfferFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
IntroductionFragment.java
public class IntroductionFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(
R.layout.introductionform_layout, container, false);
return rootView;
}
}
RequirementFragment.java
public class RequirementFragment extends Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(
R.layout.requirementFragment_layout, container, false);
return rootView;
}
}
Just give this a try
Inside your RequirementFragment.java add the onResume method as below:
public class RequirementFragment extends Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(
R.layout.requirementFragment_layout, container, false);
return rootView;
}
#Override
public void onResume() {
super.onResume();
Toast.makeText(getActivity(), "Just check if you see this every time", Toast.LENGTH_SHORT).show();
}
}
Now run your code. In case you get the Toast every time you go back and forth then we can proceed.
I have an Activity with two Action bar tabs with one fragment in each tab. Everything is working properly until a screen rotation. I have references to the fragments in my activity. If i call a method of the fragmet from my activity and that method call getActivity(), the getActivity() return null.
I don't know if i shouldn't have references to the fragments as member fields of my Activity class. If i can't keep that reference in the activity class, how can i get the values of some fields in the layout of a fragment.
Here is my activity class:
public class MyActivity extends ActionBarActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private MyPagerAdapter pagerAdapter;
private ActionBar actionBar;
DetallesAvisoFragment fragment1;
DetallesPiezaFragment fragment2;
ActionMode actionMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_avisos);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
viewPager = (ViewPager) findViewById(R.id.viewPager);
Intent intent = getIntent();
fragment1 = new Fragment1();
fragment2 = new Fragment2();
List<Fragment> fragmentList = new ArrayList<Fragment>();
fragmentList.add(fragment1);
fragmentList.add(fragment2);
pagerAdapter = new MyPagerAdapter(getSupportFragmentManager(), fragmentList);
viewPager.setAdapter(pagerAdapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int i) {
actionBar.setSelectedNavigationItem(i);
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
actionBar.addTab(actionBar.newTab().setText("Frag1 Tab").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Frag2 Tab").setTabListener(this));
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* This method work properly until screen rotation
*/
public void getValues() {
String value1 = fragment1.getValueFromSomeField();
String value2 = fragment2.getValueFromOtherField();
}
}
The FragmentPagerAdapter class:
public class MyPagerAdapter extends FragmentPagerAdapter{
List<Fragment> fragmentList;
public MyPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
fragmentList = fragments;
}
#Override
public Fragment getItem(int index) {
if (index >= fragmentList.size()) {
return null;
}
return fragmentList.get(index);
}
#Override
public int getCount() {
return fragmentList.size();
}
}
And my Fragment classes:
public class Fragment1 extends Fragment {
public Fragment1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceBundle) {
return inflater.inflate(R.layout.fragment1_layout, container, false);;
}
public String getValueFromSomeField() {
TextView testView = (TextView) getActivity().findViewById(R.id.someField);
return testView.getText().toString();
}
}
public class Fragment2 extends Fragment {
public Fragment2() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceBundle) {
return inflater.inflate(R.layout.fragment2_layout, container, false);;
}
public String getValueFromSomeOtherField() {
TextView testView = (TextView) getActivity().findViewById(R.id.someOtherField);
return testView.getText().toString();
}
}
Note: I need support for SDK 8 so I have to use Fragments using the SupportLibrary
you declare
static final String STORE_FRAGMENT1 = "fragment1";
static final String STORE_FRAGMENT2 = "fragment2";
you Override method onSaveInstanceState to save tag fragment1 and fragment 2;
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
if (fragment1 != null) {
savedInstanceState.putString(STORE_FRAGMENT1,
fragment1.getTag());
}
if (fragment2 != null) {
savedInstanceState.putString(STORE_FRAGMENT2,
fragment2.getTag());
}
super.onSaveInstanceState(savedInstanceState);
}
when OnCreated you get tag fragment1 and fragment 2 to get fragment1 and fragment2 saved before rotation
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_avisos);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
viewPager = (ViewPager) findViewById(R.id.viewPager);
Intent intent = getIntent();
//----edit-------
String TagFragment1;
String TagFragment2;
if (savedInstanceState != null) {
FragmentManager fm = getSupportFragmentManager();
TagFragment1 = savedInstanceState.getString(STORE_FRAGMENT1);
fragment1 = (SubjectFragment) fm
.findFragmentByTag(TagFragment1);
TagFragment2 = savedInstanceState.getString(STORE_FRAGMENT2);
fragment2 = (CircuitFragment) fm
.findFragmentByTag(TagFragment2);
}
else {
fragment1 = new Fragment1();
fragment2 = new Fragment2();
}
//---end--edit-----
List<Fragment> fragmentList = new ArrayList<Fragment>();
fragmentList.add(fragment1);
fragmentList.add(fragment2);
pagerAdapter = new MyPagerAdapter(getSupportFragmentManager(), fragmentList);
viewPager.setAdapter(pagerAdapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int i) {
actionBar.setSelectedNavigationItem(i);
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
actionBar.addTab(actionBar.newTab().setText("Frag1 Tab").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Frag2 Tab").setTabListener(this));
}