Fragment showing contet twice - android

I'll explain the structure of my app :
Activity --> Fragment A (Inside that fragment (A) i have 3 Fragments (B, C, D) (viewpager)) --> Inside the first fragment(B) it contains a listview. Every item from that list launches a fragment E.
So i'm facing an issue here.
When i first launch my application Everything looks fine.
But when Fragment E get's visible to the screen the tabs gets all weird and be like :
Yeap! they got duplicated.
When i click on the listview, i commit the transition between the 2 fragments from a callback in the Activity :
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, PF);
transaction.addToBackStack(null);
transaction.commit();
When i want to go back to the previous fragment:
getFragmentManager().popBackStack();
Is the previous fragment getting recreated? And what can i do to solve it?
UPDATE --CODES:
Activity :
public class MainActivity extends FragmentActivity implements
IslamToolsFragment.OnToolsSelectedListener {
FragmentTransaction transaction;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.content_frame) != null) {
if (savedInstanceState != null) {
return;
}
PagerActivity firstFragment = new PagerActivity();
getSupportFragmentManager().beginTransaction()
.add(R.id.content_frame, firstFragment).commit();
}
}
#Override
public void OnToolSelected(int position) {
// TODO Auto-generated method stub
switch (position) {
case 0:
PrayerFragment PF = new PrayerFragment();
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, PF);
transaction.addToBackStack(null);
transaction.commit();
break;
case 1:
QiblaFragment QF = new QiblaFragment();
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, QF);
transaction.addToBackStack(null);
transaction.commit();
break;
}
}
Fragment A (Which contains 3 fragments):
public class PagerActivity extends Fragment implements ActionBar.TabListener {
int NUM_PAGES = 5;
ActionBar actionBar;
private ViewPager mPager;
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mPager.setAdapter(null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
return;
} else {
actionBar = this.getActivity().getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(
getChildFragmentManager());
mPager.setAdapter(mAppSectionsPagerAdapter);
int icons[] = { R.drawable.ic_action_storage,
R.drawable.ic_action_overflow, R.drawable.ic_action_person };
mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab().setIcon(icons[i])
.setTabListener(this));
}
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View tabsview = inflater.inflate(R.layout.pager_activity, container,
false);
mPager = (ViewPager) tabsview.findViewById(R.id.pager);
return tabsview;
}
Fragnent B:
public class IslamToolsFragment extends Fragment {
OnToolsSelectedListener mCallback;
ListView islamtools;
Fragment PF = new PrayerFragment();
public interface OnToolsSelectedListener {
public void OnToolSelected(int position);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View islamtoolsview = inflater.inflate(R.layout.lvislamtools,
container, false);
if (savedInstanceState != null) {
return islamtoolsview;
}
islamtools = (ListView) islamtoolsview.findViewById(R.id.lvislamtools);
String[] title = { "Prayer Times", "Qibla", "Ahadith", "Quran",
"Hijri Calendar", "99 Names" };
IslamToolsAdapter ITA = new IslamToolsAdapter(this.getActivity(), title);
islamtools.setAdapter(ITA);
islamtools.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
mCallback.OnToolSelected(arg2);
}
});
return islamtoolsview;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnToolsSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
Thanks! is it something related to the savedinstancestate?

Your code design is a little bit wrong, fragments are actually pieces of activities, it does not make sense to me to create a fragment with more fragments inside in this situations, what you should do is create an activity for the viewpager and put into that activity your 3 fragments.
I have a similar app and this is how i handle the navigation between tabs:
pager.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) {
}
The above code changes the item selected of the action bar BUT does not change the view below the view pager tabs, you need to implement the following to do this:
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

Related

Reload Nested Fragments inside Fragment using ViewPager

i have an activity with fragments and inside one fragment i nested 3 other fragments and i use viewpager to navigate between them, but when i want to change this "main fragment" which has the nested fragments i call transaction.replace and it changes the fragment but when i come back at this fragment the nested fragments are not shown again, how can i reload them everytime i launch my fragment ?
i have tried to implement them inside my xml layout but it doesn't seems to work, i need help please !
FragmentWithViewPager:
public class FragmentWithViewPager extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_fragwithviewpager, null);
mActionBar = getActivity().getActionBar();
mActionBar.show();
mActionBar.setTitle("MyFragment");
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mPager = (ViewPager) view
.findViewById(R.id.MyFragmentMainPager);
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mPager.setCurrentItem(tab.getPosition());
tab.setIcon(tabIcon_active[tab.getPosition()]);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// /tab.setIcon(null);
tab.setIcon(tabIcon[tab.getPosition()]);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
tab.setIcon(tabIcon_active[tab.getPosition()]);
}
};
if(mActionBar.getTabCount() < 3){
for (int i=0; i < tabIcon.length; i++)
{
mActionBar.addTab(mActionBar.newTab()
.setIcon(tabIcon[i])
.setTabListener(tabListener));
}
}
mPagerAdapter = new MyFragmentsMainPagerAdapter(getFragmentManager());
new setAdapterTask().execute();
return view;
}
rivate class setAdapterTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
mPager.setAdapter(mPagerAdapter);
mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
});
}
}
The Fragment that has the 3 other Fragments nested with the Viewpager should use the ChildFragmentManager.
In your activity you have your main_fragment_container in the xml that you replace or add your fragments. Correct? If true then inside the Fragment that has the Viewpager all the fragment transactions are automatically done for you if you used a FragmentPagerAdapter to accompany the Viewpager.
Then If you replace or add fragments in your main_fragment_container should not affect the contents of the Viewpager at all. When you reload the fragment with the viewpager the viewpager will reload as well if you have passed it the ChildFragmentManager.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_parent, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ViewPager mViewPager = (ViewPager) view.findViewById(R.id.viewPager);
mViewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 4;
}
#Override
public Fragment getItem(int position) {
Bundle args = new Bundle();
args.putInt(TextViewFragment.POSITION_KEY, position);
return TextViewFragment.newInstance(args);
}
}
hide(MainFragment)
add(NewFragment)->
remove or hide(NewFragment)
show(MainFragment).
getSupportFragmentManager().beginTransition().hide(MainFragment).commit().
getSupportFragmentManager().beginTransition().add(R.id.containerid,MainFragment).commit().

how to display toast messages for each tab in swipe tab in android?

when i run this code,the toast in two different fragments are displayed on one tab. when i swipe to next tab nothing is displayed.
this is is my main tab activity:
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Offers", "Distance", "Happy Hours","Shop List" };
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
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) {
}
}
this is adapter class :
public class TabsPagerAdapter extends FragmentStatePagerAdapter {
Bundle bundle = new Bundle();
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
Fragment of = new OfferFragment();
bundle.putString("OfferFragment", "OfferFragment");
of.setArguments(bundle);
return of;
case 1:
Fragment df = new DistanceFragment();
bundle.putString("DistanceFragment", "DistanceFragment");
df.setArguments(bundle);
return df;
case 2:
Fragment hf = new HappyHoursFragment();
bundle.putString("HappyHoursFragment", "HappyHoursFragment");
hf.setArguments(bundle);
return hf;
case 3:
Fragment sf = new ShoplistFragment();
bundle.putString("ShoplistFragment", "ShoplistFragment");
sf.setArguments(bundle);
return sf;
}
return null;
}
#Override
public int getCount() {
return 4;
}
}
this is my first fragment :
public class OfferFragment extends Fragment {
private String name;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// public static final String ARG_OBJECT = "object";
View rootView = inflater.inflate(R.layout.offerfragment, container,
false);
Bundle args = getArguments();
TextView txtview = (TextView) rootView.findViewById(R.id.offer);
name = args.getString("OfferFragment");
txtview.setText(args.getString("OfferFragment"));
display();
return rootView;
}
private void display() {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), name, Toast.LENGTH_SHORT).show();
}
}
this is my second fragment :
public class DistanceFragment extends Fragment {
private String name;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.distancefragment, container, false);
Bundle args = getArguments();
TextView txtview = (TextView) rootView.findViewById(R.id.distance);
name = args.getString("DistanceFragment");
txtview.setText(args.getString("DistanceFragment"));
display();
return rootView;
}
private void display() {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), name, Toast.LENGTH_SHORT).show();
}
}
any suggestions are appreciated. am stuck with this.
This is because next fragment is created by pager
before showing toast check if that fragment is visible or not
if(fragmentName.this.isVisible())
{
// do your stuff here
}
Write onResume() in every fragment class.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
//Display Toast message here
}
}

android actionbar tab viewpage AsyncTask first tab is empty when started

it is a few days I try to solve this problem whitout success. Please help me.
I use the tabs navigation with viewpager.There are four fragments. I use async task for download the data I need to put in the view. when the app is started, the first fragments is ampty. But when i swipe to the second or the third, they have data. if i swipe from the second to the first, it has data too. so i guess i may be something wrong with notifyDataSetChanged, but i tried and it doesnt work.
MainActivity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
final ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(1);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
//private ArrayList hasLoadedPages = new ArrayList<Integer>();
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(
actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
//case 0:
// return new LaunchpadSectionFragment();
default:
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
fragment.setArguments(args);
return fragment;
}
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
String str="";
if (position==0){
str = "one";
}else if(position==1){
str = "two";
}else if(position==2){
str = "three";
}else if(position==3){
str = "four";
}
return str;
}
#Override
public void notifyDataSetChanged()
{
super.notifyDataSetChanged();
}
}
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
Bundle args = getArguments();
mCid = args.getInt(ARG_SECTION_NUMBER);
mNewsData = new ArrayList<HashMap<String,Object>>();
mNewsList = (ListView)getView().findViewById(android.R.id.list);
mNewsListAdapter = new SimpleAdapter(this.getActivity(), mNewsData, R.layout.newslist_item,
new String[]{"newslist_item_title","newslist_item_digest","newslist_item_source","newslist_item_ptime"},
new int[]{R.id.newslist_item_title,R.id.newslist_item_digest,R.id.newslist_item_source,R.id.newslist_item_ptime});
View loadMoreLayout = this.getLayoutInflater(savedInstanceState).inflate(R.layout.loadmore, null);
mNewsList.setAdapter(mNewsListAdapter);
mNewsList.addFooterView(loadMoreLayout);
mNewsList.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent intent = new Intent(getActivity(), NewsDetailsActivity.class);
startActivity(intent);
intent.putExtra("newsDate", mNewsData);
intent.putExtra("position", position);
startActivity(intent);
}
});
mLoadMoreBtn = (Button)getView().findViewById(R.id.loadmore_btn);
mLoadMoreBtn.setOnClickListener(loadMoreListener);
loadNewsAsyncTask = new LoadNewsAsyncTask();
loadNewsAsyncTask.execute(mCid,0,true);
}
}
private static class LoadNewsAsyncTask extends AsyncTask<Object, Integer, Integer>
{
#Override
protected void onPreExecute()
{
mLoadMoreBtn.setText(R.string.loadmore_txt);
}
#Override
protected Integer doInBackground(Object... params)
{
return getSpeCateNews((Integer)params[0],mNewsData,(Integer)params[1],(Boolean)params[2]);
}
#Override
protected void onPostExecute(Integer result)
{
switch (result)
{
case NONEWS:
mLoadMoreBtn.setText(R.string.no_news);
break;
case NOMORENEWS:
mLoadMoreBtn.setText(R.string.no_more_news);
break;
case LOADERROR:
mLoadMoreBtn.setText(R.string.load_news_failure);
break;
}
mNewsListAdapter.notifyDataSetChanged();
mLoadMoreBtn.setText(R.string.loadmore_btn);
}
}
You are using FragmentPagerAdapter please change it to FragmentStatePagerAdapter and run again
Difference between FragmentPagerAdapter and FragmentStatePagerAdapter
About FragmentPagerAdapter Google's guide says:
This version of the pager is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs. The fragment of each page the user visits will be kept in memory, though its view hierarchy may be destroyed when not visible. This can result in using a significant amount of memory since fragment instances can hold on to an arbitrary amount of state. For larger sets of pages, consider FragmentStatePagerAdapter.
And about FragmentStatePagerAdapter:
This version of the pager is more useful when there are a large number of pages, working more like a list view. When pages are not visible to the user, their entire fragment may be destroyed, only keeping the saved state of that fragment. This allows the pager to hold on to much less memory associated with each visited page as compared to FragmentPagerAdapter at the cost of potentially more overhead when switching between pages.

Calling a Fragment from another fragment

I have a slinding tab with 3 fragments in it. The first fragment has a button which should open a fragment under the same sliding tab.
I have the following view:
https://drive.google.com/file/d/0B1QZMHJgpviceXlOWWFUdHdnTTQ/edit?usp=sharing
The final view i want on button click from above is as follows:
https://drive.google.com/file/d/0B1QZMHJgpvicZzlSeXhLTFFlNE0/edit?usp=sharing
I tried using replace but the fragments overlap each other.
The code for the fragmentactivity, adapter and a fragment is as follows:
public class Slidingtab extends FragmentActivity implements
ActionBar.TabListener{
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Post", "Recent", "Search" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slidingtab);
Log.d("Slding tab", "started");
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener((TabListener) this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
Log.d("Slding tab", "ended");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.slidingtab, menu);
return true;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
Adapter
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
Log.d("adapter constructor", "started");
}
#Override
public Fragment getItem(int index) {
Log.d("adapter", "started");
switch (index) {
case 0:
// Top Rated fragment activity
return new Homefragment();
case 1:
// Games fragment activity
return new Recentfragment();
case 2:
// Movies fragment activity
return new Searchfragment();
}
Log.d("adapter", "ended");
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
HomeFragment
public class Homefragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("Home fragment", "started");
View rootView = inflater.inflate(R.layout.activity_homefragment, container, false);
Log.d("Home fragment", "ended");
return rootView;
}
}
I have the button in this fragment. I want the button click to open a fragment.
Any help?
Without seeing your code, I can't tell definitively, but you can try something like this:
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
Check out tutorial for more.

Tabs disappear after loading the fragments in a tabbed layout

I succeeded in make a Tabbed Layout, but I have a concern. tabs appear but disappear just after loading the first fragment. i dont have lot of idea it is due to what. This the code to try to find the error.
The onCreateView of the fragment which on i display the cotaint.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_clubs_pages, container, false);
// Initilization
viewPager = (ViewPager) v.findViewById(R.id.pager);
actionBar = getActivity().getActionBar();
mAdapter = new TabsPagerAdapter(getChildFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
return v;
}
The Main Class :
public class ClubsPages extends android.support.v4.app.Fragment implements ActionBar.TabListener {
private OnFragmentInteractionListener mListener;
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = {"Clubs", "Pages"};
// TODO: Rename and change types and number of parameters
public static ClubsPages newInstance() {
ClubsPages fragment = new ClubsPages();
return fragment;
}
public ClubsPages() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_clubs_pages, container, false);
// Initilization
viewPager = (ViewPager) v.findViewById(R.id.pager);
actionBar = getActivity().getActionBar();
mAdapter = new TabsPagerAdapter(getChildFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
/*viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});*/
actionBar.show();
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
I said that the tabs disappear just after loading the first fragment. so any help please ?

Categories

Resources