I am working on a card swipe and card flip functionality and I am using ViewPager and fragments.
My problem is I am not able to update TextView inside fragments as I swipe the card from left to right or right to left but when I flip the card it update the UI.
I tried everything which is available over Internet but none of the soltuion is working for me.
I am following this link https://github.com/jamesmccann/android-view-pager-cards
Here is my code
public class CardContainerFragment extends Fragment {
private boolean cardFlipped = false;
static TextView textview;
public CardContainerFragment() {
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_card_container, container, false);
LinearLayout ll = (LinearLayout)rootView.findViewById(R.id.layout);
rootView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flipCard();
}
});
getChildFragmentManager()
.beginTransaction()
.add(R.id.container, new CardFrontFragment())
.commit();
Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
return rootView;
}
final Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
int page = CardActivity.mViewPager.getCurrentItem();
int page_index = page+1;
String current_page = page_index + " of " + card_activity.deck_map.size();
CardActivity.tv.setText(current_page);
super.handleMessage(msg);
}
};
public void flipCard() {
Fragment newFragment = null;
Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
if (cardFlipped) {
newFragment = new CardFrontFragment();
} else {
newFragment = new CardBackFragment();
}
getChildFragmentManager()
.beginTransaction()
.setCustomAnimations(
R.animator.card_flip_right_in, R.animator.card_flip_right_out,
R.animator.card_flip_left_in, R.animator.card_flip_left_out)
.replace(R.id.container, newFragment)
.commit();
cardFlipped = !cardFlipped;
}
public static class CardFrontFragment extends Fragment {
public CardFrontFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_card, container, false);
textview = (TextView)rootView.findViewById(R.id.card_front);
String card_front_string = card_activity.arraylst.get(CardActivity.mViewPager.getCurrentItem());
Log.e("current Item",CardActivity.mViewPager.getCurrentItem()+"");
String complete_text = card_front_string +" \n \n + \n Tap now to flip this card.";
textview.setText(complete_text);
return rootView;
}
}
public static class CardBackFragment extends Fragment {
public CardBackFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_card_back, container, false);
TextView textview = (TextView)rootView.findViewById(R.id.card_back);
textview.setMovementMethod(new ScrollingMovementMethod());
String card_front_string = card_activity.arraylst.get(CardActivity.mViewPager.getCurrentItem());
String deck_data = card_activity.deck_map.get(card_front_string);
textview.setText(deck_data);
return rootView;
}
}
Here is my adapter code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.card_example);
tv = (TextView)findViewById(R.id.tv_card_number);
tv1 = (TextView)findViewById(R.id.tv_card_index);
FragmentManager m = getFragmentManager();
CardPagerAdapter adapter = new CardPagerAdapter(m);
index = getIntent().getStringExtra("index");
card_activity.cardCounter = Integer.parseInt(index);
int count = card_activity.cardCounter;
int final_count = count+1;
String current_page = final_count+" of "+card_activity.deck_map.size();
//CardActivity.tv.setText(current_page);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
// mViewPager.setAllowedSwipeDirection(CustomViewPager.SwipeDirection.all);
mViewPager.setAdapter(adapter);
mViewPager.setCurrentItem(card_activity.cardCounter);
//mViewPager.setOffscreenPageLimit(1);
//mViewPager.setOnPageChangeListener(new pagechangelistener())
//Log.e("current Item",CardActivity.mViewPager.getCurrentItem()+"");
}catch(Exception e){
e.printStackTrace();
}
}
public class CardPagerAdapter extends android.support.v13.app.FragmentStatePagerAdapter {
public CardPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
mViewPager.setOffscreenPageLimit(0);
int page = mViewPager.getCurrentItem();
int page_index = page+1;
String current_page = " of " + card_activity.deck_map.size();
tv.setText(current_page);
tv1.setText(String.valueOf(page_index));
CardContainerFragment cardContainerFragment = new CardContainerFragment();
cardContainerFragment.current_index_front = page;
cardContainerFragment.current_index_back = page;
String card_front_string = card_activity.arraylst.get(page);
CardContainerFragment.complete_text_front = card_front_string +" \n \n + \n Tap now to flip this card.";
Bundle b = new Bundle();
b.putInt("index",page);
CardContainerFragment.complete_text_back = card_activity.deck_map.get(card_front_string);
cardContainerFragment.setArguments(b);
return cardContainerFragment;
}
#Override
public int getCount() {
int len = card_activity.deck_map.size();
return len;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Please let me know what I am doing wrong here.
Thanks in advance
Finally I am able to do this with some efforts.
After searching, I get to know that getItems (The method in CardPagerAdapter) is called two times because Android creates one extra fragments for smooth transition and I was sending or getting wrong position of fragments from getItems.
By letting the android to create one extra fragment and by sending correct position I am able to solve this issue.
Here is my updated code
public class CardActivity extends android.support.v4.app.FragmentActivity {
public TextView tv;
public static String index=null;
public static ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.card_example);
tv = (TextView)findViewById(R.id.tv_card_number);
FragmentManager m = getFragmentManager();
CardPagerAdapter adapter = new CardPagerAdapter(m);
index = getIntent().getStringExtra("index");
card_activity.cardCounter = Integer.parseInt(index);
int count = card_activity.cardCounter;
int final_count = count+1;
String current_page = final_count+" of "+card_activity.deck_map.size();
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mViewPager.setOffscreenPageLimit(0);
mViewPager.setAdapter(adapter);
mViewPager.setCurrentItem(card_activity.cardCounter);
String current_page_temp =final_count+" of " + card_activity.deck_map.size();
tv.setText(current_page_temp);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Log.e("aaa",position+"");
String current_page = position+1 + " of " + card_activity.deck_map.size();
tv.setText(current_page);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}catch(Exception e){
e.printStackTrace();
}
}
public class CardPagerAdapter extends android.support.v13.app.FragmentStatePagerAdapter {
public CardPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
CardContainerFragment cardContainerFragment = new CardContainerFragment();
Bundle b = new Bundle();
b.putInt("index",i);
cardContainerFragment.setArguments(b);
return cardContainerFragment;
}
#Override
public int getCount() {
int len = card_activity.deck_map.size();
return len;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
}
==================================================================
public class CardContainerFragment extends Fragment {
private boolean cardFlipped = false;
int current_index=0;
static int pos = 0;
public CardContainerFragment() {
/*setHasOptionsMenu(true);*/
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_card_container, container, false);
LinearLayout ll = (LinearLayout)rootView.findViewById(R.id.layout);
rootView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flipCard();
}
});
pos = getArguments().getInt("index");
getChildFragmentManager()
.beginTransaction()
.add(R.id.container, new CardFrontFragment().newInstance(pos))
.commit();
card_activity.tempCounter = card_activity.tempCounter+1;
return rootView;
}
public void flipCard() {
Fragment newFragment = null;
CardFrontFragment cardFrontFragment = null;
CardBackFragment cardBackFragment = null;
if (cardFlipped) {
newFragment = CardFrontFragment.newInstance(CardActivity.mViewPager.getCurrentItem());
} else {
newFragment = cardBackFragment.newInstance(CardActivity.mViewPager.getCurrentItem());
}
getChildFragmentManager()
.beginTransaction()
.setCustomAnimations(
R.animator.card_flip_right_in, R.animator.card_flip_right_out,
R.animator.card_flip_left_in, R.animator.card_flip_left_out)
.replace(R.id.container, newFragment)
.commit();
cardFlipped = !cardFlipped;
}
public static class CardBackFragment extends Fragment {
public CardBackFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView_back = inflater.inflate(R.layout.fragment_card_back, container, false);
TextView textview_back = (TextView)rootView_back.findViewById(R.id.card_back);
textview_back.setMovementMethod(new ScrollingMovementMethod());
String text = getArguments().getString("back_text");
textview_back.setText(text);
return rootView_back;
}
static CardBackFragment newInstance(int position) {
CardBackFragment cardBackFragment = new CardBackFragment();
Bundle args = new Bundle();
String card_front_string = card_activity.arraylst.get(position);
String text = card_activity.deck_map.get(card_front_string);
args.putString("back_text", text);
cardBackFragment.setArguments(args);
return cardBackFragment;
}
}
public static class CardFrontFragment extends Fragment {
public CardFrontFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView_front = null;
rootView_front = inflater.inflate(R.layout.fragment_card, container, false);
TextView textview_front = (TextView)rootView_front.findViewById(R.id.card_front);
String text = getArguments().getString("front_text");
textview_front.setText(text);
return rootView_front;
}
static CardFrontFragment newInstance(int position) {
CardFrontFragment cardFrontFragment = new CardFrontFragment();
Bundle args = new Bundle();
String card_front_string = card_activity.arraylst.get(position);
String text = card_front_string +" \n \n + \n Tap now to flip this card.";
args.putString("front_text", text);
cardFrontFragment.setArguments(args);
return cardFrontFragment;
}
}
}
As #david-rawson says
Don't use static fields CardActivity.mViewPager. See https://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
Reason for this is that the ViewPager might/will create the views of your fragments before they are displayed to ensure you get that smooth animation that people love ViewPagers for. So the mViewPager calls a number of fragments createView() function at the same time, and at that time the mViewPager has an index for .getCurrentItem() which goes to the CardContainer on the page being viewed.
A better option would be for you to pass CardContainerFragment a String argument with the value for "completeText" which you want it to display whenever it creates either CardBackFragment or CardFrontFragment.
Go through this for more details.
You just have to set data to text view which is used in CardFrontFragment.
Here when ever a swipe happens onCreateView() of CardContainerFragment is called.
You are adding CardFrontFragment every time when onCreateView() is called. you need to use text view of CardFrontFragment instead of using textview of activity.
Just replace CardActivity.tv.setText(current_page);
with textView.setText(current_page);
Make sure the textview you have used in CardFrontFragment is available at class level.
you are using static fragments so textview must be static.
private static TextView textView=null;
Hope this will work for you :)
Have you tried this:
tv.post(new Runnable() {
#Override
public void run() {
CardActivity.tv.setText(current_page);
}
});
I did something similar wihtin my App, and I manage the display of my TextView into the OnCreateView, with a switch case.
I tried to implent your code but did not have all your materials (like custom animator).
You should then try something like that:
public class CardContainerFragment extends AppCompatActivity {
private boolean cardFlipped = false;
static TextView textview;
/*public CardContainerFragment() {
setHasOptionsMenu(true);
}*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_name);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
/*
The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
// This method will be invoked when a new page becomes selected.
#Override
flipCard();
#Override
public void onPageSelected(int position) {
}
// This method will be invoked when the current page is scrolled
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// Code goes here
}
// Called when the scroll state changes:
// SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
#Override
public void onPageScrollStateChanged(int state) {
// Code goes here
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_welcome, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Initializing data
Context context = getContext();
View rootView = inflater.inflate(R.layout.fragment_card, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.txtView);
int fragment = getArguments().getInt(ARG_SECTION_NUMBER);
switch (fragment)
{
case 1: //front card
String card_front_string = card_activity.arraylst.get(CardActivity.mViewPager.getCurrentItem());
Log.e("current Item",CardActivity.mViewPager.getCurrentItem()+"");
String complete_text = card_front_string +" \n \n + \n Tap now to flip this card.";
textview.setText(complete_text);
getChildFragmentManager()
.beginTransaction()
.add(R.id.container, new CardFrontFragment())
.commit();
Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
return rootView;
case 2: //back card
TextView textview = (TextView)rootView.findViewById(R.id.card_back);
textview.setMovementMethod(new ScrollingMovementMethod());
String card_front_string = card_activity.arraylst.get(CardActivity.mViewPager.getCurrentItem());
String deck_data = card_activity.deck_map.get(card_front_string);
textview.setText(deck_data);
getChildFragmentManager()
.beginTransaction()
.add(R.id.container, new CardFrontFragment())
.commit();
Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
return rootView;
default:
return rootView;
}
}
}
final Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
int page = CardActivity.mViewPager.getCurrentItem();
int page_index = page+1;
String current_page = page_index + " of " + card_activity.deck_map.size();
CardActivity.tv.setText(current_page);
super.handleMessage(msg);
}
};
public void flipCard() {
Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
getChildFragmentManager()
.beginTransaction()
.setCustomAnimations(
R.animator.card_flip_right_in, R.animator.card_flip_right_out,
R.animator.card_flip_left_in, R.animator.card_flip_left_out)
.replace(R.id.container, newFragment)
.commit();
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
}
return null;
}
}
The textView is displayed on your page, and when selecting the change, the content of your textview will be changed.
Related
This question is something serious for me , i need to someone help me regarding this. Actually i am creating an RSS feed app by combining navigation drawer and view pager tabbed activity. i want to pass a string value from one fragment to other fragment. here is the thing. It was working properly when it was with the navigation drawer activity but after combining with view-pager , String is not passing to other fragment through bundle, i can't find the error because its not showing any error,
This is from i am passing string
public class RssFragment extends Fragment implements OnItemClickListener {
private ProgressBar progressBar;
private ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
listView = (ListView) view.findViewById(R.id.listView);
listView.setOnItemClickListener(this);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
startService();
}
private void startService() {
Intent intent = new Intent(getActivity(), RssService.class);
getActivity().startService(intent);
}
/**
* Once the {#link RssService} finishes its task, the result is sent to this BroadcastReceiver
*/
private BroadcastReceiver resultReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
progressBar.setVisibility(View.GONE);
List<RssItem> items = (List<RssItem>) intent.getSerializableExtra(RssService.ITEMS);
if (items != null) {
RssAdapter adapter = new RssAdapter(getActivity(), items);
listView.setAdapter(adapter);
} else {
Toast.makeText(getActivity(), "An error occurred while downloading the rss feed.",
Toast.LENGTH_LONG).show();
}
}
};
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
RssAdapter adapter = (RssAdapter) parent.getAdapter();
RssItem item = (RssItem) adapter.getItem(position);
Uri uri = Uri.parse(item.getDescription());
String string;
string=uri.toString();
result Des_1=new result();
FragmentManager fragmentManager1 =getActivity().getSupportFragmentManager();
fragmentManager1.beginTransaction().replace(R.id.content_main_layout_frame,Des_1 ).addToBackStack("fragBack").commit();
result ldf = new result();
Bundle args = new Bundle();
args.putString("YourKey", string);
ldf.setArguments(args);
getFragmentManager().beginTransaction().add(R.id.content_main_layout_frame, ldf).commit();
}
#Override
public void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter(RssService.ACTION_RSS_PARSED);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(resultReceiver, intentFilter);
}
#Override
public void onStop() {
super.onStop();
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(resultReceiver);
}
}
This is how i am receiving the string
public class result extends Fragment {
public result() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview=inflater.inflate(R.layout.fragment_result,container,false);
Bundle bundle = getArguments();
TextView textView=(TextView)rootview.findViewById(R.id.distext);
if(bundle != null) {
String value = bundle.getString("YourKey");
textView.setText(value);
// Toast.makeText(getActivity(), value,
// Toast.LENGTH_LONG).show();
}
return rootview;
}
}
I pleasing someone to figure it out. i repeat it was working but now its not
It is another fragment
public class datafragment extends Fragment {
View view;
ViewPager viewPager;
TabLayout tabLayout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view= inflater.inflate(R.layout.sample,container,false);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPager.setAdapter(new sliderAdapter(getChildFragmentManager()));
tabLayout = (TabLayout) view.findViewById(R.id.sliding_tabs);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return view;
}
private class sliderAdapter extends FragmentPagerAdapter{
final String tabs[]={"tab1", "tab2","tab3"};
public sliderAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0:
fragment = new RssFragment();
break;
case 1:
fragment = new RssFragment();
break;
case 2:
fragment = new RssFragment();
break;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
}
}
Try the below one,
ldf = new result();
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction =
getActivity().getSupportFragmentManager().beginTransaction();
bundle.putString("key","value");
ldf.setArguments(bundle);
fragmentTransaction.addToBackStack("fragBack");
fragmentTransaction.replace(R.id.content_main_layout_frame, ldf);
fragmentTransaction.commit();
Remove both the transaction and add the below code instead,
ldf = new result();
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction =
getActivity().getSupportFragmentManager().beginTransaction();
bundle.putString("key","value");
ldf.setArguments(bundle);
fragmentTransaction.addToBackStack("fragBack");
fragmentTransaction.add(R.id.content_main_layout_frame, ldf);
fragmentTransaction.commit();
Let me know if that helps!
Try this
public class result extends Fragment {
public result() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview=inflater.inflate(R.layout.fragment_result,container,false);
TextView textView=(TextView)rootview.findViewById(R.id.distext);
if(savedInstanceState!= null) {
String value = savedInstanceState.getString("YourKey");
textView.setText(value);
// Toast.makeText(getActivity(), value,
// Toast.LENGTH_LONG).show();
}
return rootview;
}
}
So, as the title states, I wish to produce some amount of layouts within a Fragment which is in turn within a fragment. The number of layouts depends on the number of columns returned from a database, and the number of columns returned depends on which Fragment the user is currently on.
The first fragments are a BottomNavigation View, then the second set of Fragments are a range of swipe panels within each part of the BottomNavigation. It is in these fragments that I want to produce the variable number of layouts.
Here is a screenshot of what I'm looking to achieve
I was trying to create the Layouts within the OnCreateView() method for the inner Fragment but that is causing errors. I know that OnCreateView() returns a view so that must be wrong to try to create these layouts here.
I essentially have my main class which is divided into the 4 bottomNav fragments, each of which are divided into between 2-6 Fragments themselves.
Where should I be creating these layouts? Is there some other way to achieve the objective? Why is it not possible to create a layout within OnCreateView()? I'm very confused by the whole process, though the issue is probably a simple enough fix. Any help would be much appreciated.
If necessary I can provide code, though hopefully this is a simple enough issue that it is not needed.
EDIT: Below I have added the code I have so far:
MainActivity (which produces the BottomNavigation):
public class MainActivity extends AppCompatActivity {
private static final String SELECTED_ITEM = "arg_selected_item";
private BottomNavigationView mBottomNav;
private int mSelectedItem;
public static int numTabs;
public static String fragType;
public static String[] headings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBottomNav = (BottomNavigationView) findViewById(R.id.navigation);
mBottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
selectFragment(item);
return true;
}
});
MenuItem selectedItem;
if (savedInstanceState != null) {
mSelectedItem = savedInstanceState.getInt(SELECTED_ITEM, 0);
selectedItem = mBottomNav.getMenu().findItem(mSelectedItem);
} else {
selectedItem = mBottomNav.getMenu().getItem(0);
}
selectFragment(selectedItem);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(SELECTED_ITEM, mSelectedItem);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
MenuItem homeItem = mBottomNav.getMenu().getItem(0);
if (mSelectedItem != homeItem.getItemId()) {
// select home item
selectFragment(homeItem);
} else {
super.onBackPressed();
}
}
private void selectFragment(MenuItem item) {
Fragment frag = null;
// init corresponding fragment
switch (item.getItemId()) {
//USER PROFILE
case R.id.menu_home:
numTabs = 3;
fragType = getString(R.string.text_home);
headings = new String[numTabs];
headings[0] = "PROFILE HEADING 1";
headings[1] = "PROFILE HEADING 2";
headings[2] = "PROFILE HEADING 3";
frag = MenuFragment.newInstance(fragType);
break;
//DISCOVER
case R.id.menu_search:
fragType = getString(R.string.text_search);
numTabs = 6;
headings = new String[numTabs];
headings[0] = "DISCOVER HEADING 1";
headings[1] = "DISCOVER HEADING 2";
headings[2] = "DISCOVER HEADING 3";
headings[3] = "DISCOVER HEADING 4";
headings[4] = "DISCOVER HEADING 5";
headings[5] = "DISCOVER HEADING 6";
frag = MenuFragment.newInstance(fragType);
break;
//SCHEDULE
case R.id.menu_notifications:
fragType = getString(R.string.text_notifications);
numTabs = 2;
headings = new String[numTabs];
headings[0] = "SCHEDULE HEADING 1";
headings[1] = "SCHEDULE HEADING 2";
frag = MenuFragment.newInstance(fragType);
break;
//FOLLOWED
case R.id.menu_followed:
fragType = getString(R.string.text_follow);
numTabs = 3;
headings = new String[numTabs];
headings[0] = "FOLLOWED HEADING 1";
headings[1] = "FOLLOWED HEADING 2";
headings[2] = "FOLLOWED HEADING 3";
frag = MenuFragment.newInstance(fragType);
}
// update selected item
mSelectedItem = item.getItemId();
// uncheck the other items.
for (int i = 0; i< mBottomNav.getMenu().size(); i++) {
MenuItem menuItem = mBottomNav.getMenu().getItem(i);
menuItem.setChecked(menuItem.getItemId() == item.getItemId());
}
if (frag != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.container, frag, frag.getTag());
ft.commit();
}
}
}
Here's the MenuFragment class:
public class MenuFragment extends Fragment {
private static final String ARG_TEXT = "arg_text";
private String mText;
private TextView mTextView;
private Button contactButton;
private Button logoutButton;
public static Fragment newInstance(String text) {
Fragment frag = new MenuFragment();
Bundle args = new Bundle();
args.putString(ARG_TEXT, text);
frag.setArguments(args);
return frag;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View result = inflater.inflate(R.layout.fragment_menu, container, false);
ViewPager view = (ViewPager)result.findViewById(R.id.pager);
view.setAdapter(buildAdapter());
return(result);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (savedInstanceState == null) {
Bundle args = getArguments();
mText = args.getString(ARG_TEXT);
} else {
mText = savedInstanceState.getString(ARG_TEXT);
}
// initialize views
mTextView = (TextView) view.findViewById(R.id.text);
contactButton = (Button) view.findViewById(R.id.contactButton);
logoutButton = (Button) view.findViewById(R.id.logoutbutton);
// set text
mTextView.setText(mText);
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(ARG_TEXT, mText);
super.onSaveInstanceState(outState);
}
private PagerAdapter buildAdapter() {
return(new MidSectionAdapter(getActivity(), getChildFragmentManager()));
}
}
And here is the MidSectionAdapter:
public class MidSectionAdapter extends FragmentPagerAdapter {
Context ctxt=null;
String title;
public MidSectionAdapter(Context ctxt, FragmentManager mgr) {
super(mgr);
this.ctxt=ctxt;
}
#Override
public int getCount() {
return(MainActivity.numTabs);
}
#Override
public Fragment getItem(int position) {
if(MainActivity.fragType.equals("MY PROFILE")) {
return(ProfileFragment.newInstance(position));
} else if(MainActivity.fragType.equals("DISCOVER")) {
return(DiscoverFragment.newInstance(position));
} else if(MainActivity.fragType.equals("SCHEDULE")) {
return(ScheduleFragment.newInstance(position));
} else {
return(UpComingFragment.newInstance(position));
}
}
#Override
public String getPageTitle(int position) {
if(MainActivity.fragType.equals("MY PROFILE")) {
title = ProfileFragment.getTitle(ctxt, position);
} else if(MainActivity.fragType.equals("DISCOVER")) {
title = DiscoverFragment.getTitle(ctxt, position);
} else if(MainActivity.fragType.equals("SCHEDULE")) {
title = ScheduleFragment.getTitle(ctxt, position);
} else {
title = UpComingFragment.getTitle(ctxt, position);
}
return(title);
}
}
And here is an example of the inner Fragment (I have reverted it back to the code I had before I was having the issue, so it doesn't do much other than display "in panel x"):
public class ScheduleFragment extends Fragment {
private static final String KEY_POSITION="position";
private TextView panelView;
private static String head;
private static int panelPosition;
String panelCheck;
static ScheduleFragment newInstance(int position) {
ScheduleFragment frag=new ScheduleFragment();
Bundle args=new Bundle();
args.putInt(KEY_POSITION, position);
frag.setArguments(args);
return(frag);
}
static String getTitle(Context ctxt, int position) {
head = MainActivity.headings[position];
panelPosition = position;
return(head);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View result=inflater.inflate(R.layout.schedule_content, container, false);
panelView = (TextView) result.findViewById(R.id.testFrag);
int position=getArguments().getInt(KEY_POSITION, -1);
if(getTitle(getActivity(), position).equals(MainActivity.headings[0])) {
//MAY NOT NEED THIS NITIAL IF STATEMENT
panelCheck = "in first panel";
} else {
//tableType = "Venue";
panelCheck = "in second panel";
}
panelView.setText(panelCheck);
return(result);
}
}
By the way, you can create/add/replace n of fragments in Android Activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity)
//or
LinearLayout layout = getLayoutInflator.inflate(R.layout.your_activity);
setContentView(layout)
}
Similarly you can create n of Views within Activity as well as Fragment.
private LayoutInflater fragmentInflater,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
this.fragmentInflater = inflater;
View view = inflater.inflate(R.layout.alto_dialog, container, false);
return view;
}
Basically you can create Views/ViewGroups add/remove views at any time you want. What you want is the fragmentInflater object.
According to your screenshot req, you may need a ListView or RecyclerView with different view types. If your list is small you can simply go head with ScrollView + LinearLayout
Hope this helps.
My app has a tab bar that should be visible at all times. The first tab contains a ListFragment. When I click on an item within, it loads a new activity that creates a detail fragment displaying the contents of the object in the list. I would like to display this content without having to start a new activity because it also destroys the tab bar!
Any help would be greatly appreciated!
To illustrate, here are some screenshots and code:
This is the code for the FragmentActivity that creates the tabs:
public class MainFragmentActivity extends FragmentActivity
implements ActionBar.TabListener {
SectionsPagerAdapter sectionsPagerAdapter = null;
ViewPager viewPager = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
getActionBar().setDisplayShowHomeEnabled(false);
getActionBar().setDisplayShowTitleEnabled(false);
sectionsPagerAdapter =
new SectionsPagerAdapter
(
getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(sectionsPagerAdapter);
viewPager.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
}); // End of sectionPageAdapter.
Tab browseTab = actionBar.newTab();
browseTab.setIcon(R.drawable.search);
browseTab.setTabListener(this);
actionBar.addTab(browseTab);
Tab myStuffTab = actionBar.newTab();
myStuffTab.setIcon(R.drawable.my_stuff);
myStuffTab.setTabListener(this);
actionBar.addTab(myStuffTab);
Tab profileTab = actionBar.newTab();
profileTab.setIcon(R.drawable.profile);
profileTab.setTabListener(this);
actionBar.addTab(profileTab);
Tab settingsTab = actionBar.newTab();
settingsTab.setIcon(R.drawable.settings);
settingsTab.setTabListener(this);
actionBar.addTab(settingsTab);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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) {
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Fragment browseFragment = new BrowseFragment();
Bundle browseArgs = new Bundle();
browseArgs.putInt(BrowseFragment.sectionNumberKey, position + 1);
browseFragment.setArguments(browseArgs);
return browseFragment;
case 1:
Fragment myStuffFragment = new MyStuffFragment();
Bundle myStuffArgs = new Bundle();
myStuffArgs.putInt(BrowseFragment.sectionNumberKey, position + 1);
myStuffFragment.setArguments(myStuffArgs);
return myStuffFragment;
case 2:
Fragment profileFragment = new ProfileFragment();
Bundle profileArgs = new Bundle();
profileArgs.putInt(BrowseFragment.sectionNumberKey, position + 1);
profileFragment.setArguments(profileArgs);
return profileFragment;
case 3:
Fragment settingsFragment = new SettingsFragment();
Bundle settingsArgs = new Bundle();
settingsArgs.putInt(BrowseFragment.sectionNumberKey, position + 1);
settingsFragment.setArguments(settingsArgs);
return settingsFragment;
}
return null;
}
// There are always 4 tabs
#Override
public int getCount() {
return 4;
}
// Return a CharSequence for the selected tab
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase();
case 1:
return getString(R.string.title_section2).toUpperCase();
case 2:
return getString(R.string.title_section3).toUpperCase();
case 3:
return getString(R.string.title_section4).toUpperCase();
}
return null;
}
}
} // End of class.
This is the code for the first tab:
public class BrowseFragment extends ListFragment {
public static String sectionNumberKey = "sec_num";
private String activityName = "Browse";
int currentPosition = 0;
List<Listing> listings = new ListingData().getListings();
public BrowseFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BrowseArrayAdapter adapter = new BrowseArrayAdapter(getActivity(),
R.layout.browselist_item,
listings);
setListAdapter(adapter);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_browse,
container, false);
TextView tv = (TextView) rootView.findViewById(R.id.section_label);
int intSectionNumber = getArguments().getInt(sectionNumberKey);
String numAsString = Integer.toString(intSectionNumber);
tv.setText(numAsString);
activityName += " " + numAsString;
return rootView;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position);
}
void showDetails(int index) {
currentPosition = index;
Intent intent = new Intent();
intent.setClass(getActivity(), BrowseDetailsActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
And here is the code for the Detail Activity:
public class BrowseDetailsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
BrowseDetailFragment details = new BrowseDetailFragment();
details.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
}
}
}
Basicly you just have to use the content of the onCreate method from your BrowseDetailActivity in the showDetails method of your BrowseFragment. In this way, you can drop your BrowseDetailsActivity.
BrowseFragment.java
void showDetails(int index) {
BrowseDetailFragment details = BrowseDetailFragment.newInstance(index);
getChildFragmentManager().beginTransaction().add(details).commit();
}
And use the static newInstance method inside your BrowseDetailFragment like so:
BrowseDetailFragment.java
public class BrowseDetailFragment extends Fragment {
private int position;
public static BrowseDetailFragment newInstance(int position) {
BrowseDetailFragment fragment = new BrowseDetailFragment();
fragment.position = position;
return fragment;
}
public BrowseDetailFragment() {
//Required empty constructor
}
//Lifecycle methods and logics
}
Make sure to provide some navigation option so users can return to your list.
I created a ViewPager that uses individual Fragments. There are 3, here is an example of one of them:
public class PainFragment extends Fragment {
private TextView mTxtScale;
private Button mBtnMinus;
private Button mBtnPlus;
private int mScale;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pain, container, false);
mTxtScale = (TextView)v.findViewById(R.id.scale);
mBtnMinus = (Button)v.findViewById(R.id.minus);
mBtnPlus = (Button)v.findViewById(R.id.plus);
mScale = Integer.valueOf(mTxtScale.getText().toString());
mBtnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mScale--;
if(mScale == -1) {
mScale = 9;
}
mTxtScale.setText(String.valueOf(mScale));
}
});
mBtnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mScale++;
if(mScale == 10) {
mScale = 0;
}
mTxtScale.setText(String.valueOf(mScale));
}
});
return v;
}
public static PainFragment newInstance(String text) {
PainFragment f = new PainFragment();
Bundle b = new Bundle();
//b.putString("msg", text);
f.setArguments(b);
return f;
}
public int getScale() {
int scale = Integer.valueOf(mTxtScale.getText().toString());
return scale;
}
And I instantiated the ViewPager in my MainFragment:
public class MainFragment extends Fragment {
Entry mEntry = new Entry();
ViewPager mPager;
JournalPagerAdapter mAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_screen, container, false);
mPager = (ViewPager)rootView.findViewById(R.id.pager);
mPager.setOffscreenPageLimit(2); // So all 3 pages are loaded at once.
mAdapter = new JournalPagerAdapter(getActivity().getSupportFragmentManager());
mPager.setAdapter(mAdapter);
...
I have button click listeners in the ViewPager Fragments. I would like to know the best way to set up a listener so that my main fragment can detect when a button is pressed on one of the ViewPager fragments.
/** Update - Here is my adapter class **/
public class JournalPagerAdapter extends FragmentPagerAdapter {
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public JournalPagerAdapter(FragmentManager mgr) {
super(mgr);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return PainFragment.newInstance("PainFragment");
case 1: return StressFragment.newInstance("StressFragment");
case 2: return SleepFragment.newInstance("SleepFragment");
default: return PainFragment.newInstance("PainFragment");
}
}
#Override
public int getCount() {
return 3;
}
/* Thanks to Streets of Boston (http://stackoverflow.com/questions/8785221/retrieve-a-fragment-from-a-viewpager)
* for the next 3 methods, should include in all PagerAdapters. Let's you get the fragment instances by position */
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
Second answer with pseudo example of using a ClickListener instead of the Callback. This should let you keep all logic out of the Activity.
Implement OnClickListener interface in MainFragment. Add a OnClickListener to your JournalPagerAdapter constructor. Presumably the Adapter is creating the PainFragments. Add OnClickListener to PainFragment newInstance and have the Adapter provide it when it creates each PainFragment.
public class PainFragment extends Fragment {
private TextView mTxtScale;
private Button mBtnMinus;
private Button mBtnPlus;
private int mScale;
protected OnClickListener mainClickListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pain, container, false);
mTxtScale = (TextView)v.findViewById(R.id.scale);
mBtnMinus = (Button)v.findViewById(R.id.minus);
mBtnPlus = (Button)v.findViewById(R.id.plus);
mScale = Integer.valueOf(mTxtScale.getText().toString());
mBtnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mScale--;
if(mScale == -1) {
mScale = 9;
}
mTxtScale.setText(String.valueOf(mScale));
mainClickListener.onClick(view);
}
});
mBtnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mScale++;
if(mScale == 10) {
mScale = 0;
}
mTxtScale.setText(String.valueOf(mScale));
mainClickListener.onClick(view);
}
});
return v;
}
public static PainFragment newInstance(String text, OnClickListener onClickListener) {
PainFragment f = new PainFragment();
f.mainClickListener = onClickListener;
Bundle b = new Bundle();
//b.putString("msg", text);
f.setArguments(b);
return f;
}
public int getScale() {
public class MainFragment extends Fragment implements OnClickListener {
Entry mEntry = new Entry();
ViewPager mPager;
JournalPagerAdapter mAdapter;
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_screen, container, false);
mPager = (ViewPager)rootView.findViewById(R.id.pager);
mPager.setOffscreenPageLimit(2); // So all 3 pages are loaded at once.
mAdapter = new JournalPagerAdapter(getActivity().getSupportFragmentManager(), this);
mPager.setAdapter(mAdapter);
...
public class JournalPagerAdapter extends FragmentPagerAdapter {
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
private OnClickListener mOnClickListener;
public JournalPagerAdapter(FragmentManager mgr, OnClickListener onClickListener) {
super(mgr);
mOnClickListener = onClickListener;
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return PainFragment.newInstance("PainFragment", mOnClickListener);
case 1: return StressFragment.newInstance("StressFragment", mOnClickListener);
case 2: return SleepFragment.newInstance("SleepFragment", mOnClickListener);
default: return PainFragment.newInstance("PainFragment", mOnClickListener);
}
}
...
The proper way to achieve this is probably through the use of a callback. Your fragment would utilize a normal click listener which would then use a callback to communicate back to the hosting Activity.
See the Android docs regarding communicating from a Fragment back to the Activity; then the Activity can communicate it to other Fragments.
http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
In some cases, you might need a fragment to share events with the activity. A good way to do that is to define a callback interface inside the fragment and require that the host activity implement it. When the activity receives a callback through the interface, it can share the information with other fragments in the layout as necessary.
I'm using FragmentPagerAdapter with FragmentActivity to create swipe-able Fragments.
My first fragment in that pagerAdapter look like this.
public class MySummaryFragment extends CommonFragment implements OnPageChangeListener
{
private Context mContext;
private View mMyView;
LinearLayout mDetailLayout;
TextView mDateTxtView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
System.out.println("onCreateView() Market summary");
mMyView = inflater.inflate(R.layout.my_page_summary_fragment_layout, container,false);
mDetailLayout = (LinearLayout)mMyView.findViewById(R.id.SummaryDetailLayout);
mDateTxtView = (TextView) mMyView.findViewById(R.id.txtDate);
Account_Id = AccountDetails.getInstance(mContext).getClientCodes().get(0);
sendRequest(Account_Id);
return mMyView;
}
#Override
public void onPageSelected(int arg0) {
System.out.println("inside onPageScrollStateChanged()");
System.out.println("mMyView is null ? = "+(mMyView==null));
mDateTxtView = (TextView) mMyView.findViewById(R.id.txtMarketSummaryDate);
Account_Id = AccountDetails.getInstance(mContext).getClientCodes().get(0);
mDateTxtView.setText("");
sendRequest(Account_Id);
}
}
The problem here is I'm getting NullPointerException when swipe-out to 5-6 fragments and swiping back to first fragment.
When I try to debug, I found that
mMyView is null ? = true
Why so?
Please help me.
Here is my Fragment contains the FragmentPagerAdapter,
public class MyPageDetailViewFragment extends CommonFragment {
private View mView;
Context mContext;
OnPageChangeListener pageChangeListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.my_page_fragments, null);
mContext = getActivity();
setHasOptionsMenu(false);
setupSearchBarComponent();
PagerTabStrip pagerTabStrip = (PagerTabStrip)mView. findViewById(R.id.pager_title_strip);
pagerTabStrip.setDrawFullUnderline(true);
pagerTabStrip.setTabIndicatorColor(Color.BLACK);
/** Getting a reference to the ViewPager defined the layout file */
ViewPager pager = (ViewPager) mView.findViewById(R.id.pager);
/** Getting fragment manager */
FragmentManager fm = ((HomeScreenActivity)mContext).getSupportFragmentManager();
/** Instantiating FragmentPagerAdapter */
final MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(fm);
pager.setAdapter(pagerAdapter);
pager.setCurrentItem(0);
pageChangeListener = new OnPageChangeListener() {
#Override
public void onPageSelected(int selectedIndex) {
System.out.println("selectedIndex = "+selectedIndex);
Object page = pagerAdapter.getItem(selectedIndex);
if( page instanceof OnPageChangeListener){
((OnPageChangeListener) page).onPageSelected(selectedIndex);
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
pager.setOnPageChangeListener(pageChangeListener);
return mView;
// return super.onCreateView(inflater, container, savedInstanceState);
}
And here is my implementation MyFragmentPagerAdapter,
public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
/** Constructor of the class */
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
/** This method will be invoked when a page is requested to create */
#Override
public Fragment getItem(int index) {
System.out.println("getItem = "+index);
Bundle data = new Bundle();
data.putInt("current_page", index + 1);
CommonFragment fragment = getFragment(index);
fragment.setArguments(data);
return fragment;
}
public CommonFragment getFragment(int index) {
CommonFragment fragment = null;
if(fragment == null){
if(index == 0){
fragment = new MySummaryFragment();
}else if(index == 1){
fragment = new FragmentOne();
}else if(index == 4){
fragment = new FragmentFour();
}else if(index == 5){
fragment = new FragmentFive();
}else{
fragment = new MyFragment();
}
}
return fragment;
}
/** Returns the number of pages */
#Override
public int getCount() {
return titles.length;
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
pagerAdapter.getItem(selectedIndex) actually creates a new instance of the fragment.
See this answer: https://stackoverflow.com/a/23843743/1271907
You have to keep a reference to the actual fragment.
It looks like you are calling the wrong method on the inflater.
Try to change this line:
mView = inflater.inflate(R.layout.my_page_fragments, null);
to:
mView = inflater.inflate(R.layout.my_page_fragments,container, null);