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.
Related
I would like to create an activity which shows 3 tabs. The first tab should show a user's uploaded photos the 2nd all the images a user liked, and 3rd the user's favorite images. All these data comes from a webservice.I would like to use the same fragment with it's layout file and call different URLs. The fragment implements a StringReader and populates a listview inside.
My problem is that I managed to load the Fragment in the first tab, but the second and third tabs remains empty. If I navigate to the last tab and started to navigate back, then the first tab remains empty and the second gets populated. I watched so many tutorials and red what I could reached but It seems that nothing has helped.
The Fragment instantiation in my Activity looks like this :
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public 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).
switch (position) {
case 0:
return UsersSpheresFragment.newInstance();
case 1:
return UsersSpheresFragment.newInstance();
case 2:
return UsersSpheresFragment.newInstance();
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
my fragment is :
public class UsersSpheresFragment extends Fragment {
CircleImageView userImageFragment;
TextView userNameTextFragment;
TextView nrOfSpheresFragment;
LinearLayout loadingLayoutFragment;
ListView listview_spheresFragment;
public PhotosphereListAdapter adapter;
TextView nrOfLikes;
TextView nrOfSeens;
String userId="";
String userName = "";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_spheres_fragment,container,false);
return view;
}
// newInstance constructor for creating fragment with arguments
public static UsersSpheresFragment newInstance() {
UsersSpheresFragment fragmentFirst = new UsersSpheresFragment();
return fragmentFirst;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
userImageFragment = (CircleImageView) getActivity().findViewById(R.id.userImageFragment);
userNameTextFragment = (TextView) getActivity().findViewById(R.id.userNameTextFragment);
nrOfSpheresFragment = (TextView) getActivity().findViewById(R.id.nrOfSpheresFragment);
loadingLayoutFragment = (LinearLayout) getActivity().findViewById(R.id.loadingLayoutFragment);
listview_spheresFragment = (ListView) getActivity().findViewById(R.id.listview_spheresFragment);
nrOfLikes = (TextView)getActivity().findViewById(R.id.nrOfLikes);
nrOfSeens = (TextView)getActivity().findViewById(R.id.nrOfSeens);
GlobalUserData userData = (GlobalUserData)getActivity().getApplication();
Bundle bundle = this.getArguments();
if (bundle != null) {
userId = bundle.getString("userId","");
userName = bundle.getString("userName","");
userNameTextFragment.setText(userName);
}
else{
if (userData.getUserImageLink().length() > 0) {
LoadUserImage(userData.getName(), userData.getUserImageLink());
}
userNameTextFragment.setText(userData.getName());
}
//Log.i("TAG",userData.GetAllData());
if (userId.length() > 0)
loadImagesFromAPI(MainActivity.URL_DATA+"typ=mysphere&id="+userId);
else
loadImagesFromAPI(MainActivity.URL_DATA+"typ=mysphere&id="+userData.getUserId());
listview_spheresFragment.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//send the photosphereId to the Panoviewer fragment
Bundle bundle = new Bundle();
bundle.putString("Id", view.getTag().toString());
bundle.putString("Title", ((Photosphere) adapter.getItem(position)).getTitle());
bundle.putString("Description", ((Photosphere) adapter.getItem(position)).getDescription());
bundle.putString("ThumbUrl", ((Photosphere) adapter.getItem(position)).getImageUrl());
bundle.putBoolean("ShowUserLink", userId.length() > 0 ? false : true);
//create the fragment
SimpleFragment fragment = new SimpleFragment();
fragment.setArguments(bundle);
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_main, fragment);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.addToBackStack(null);
transaction.commit();
}
});
}
public void LoadUserImage(String userName, String imageUrl){
ImageLoader imageLoader = CustomVolleyRequest.getInstance(getActivity()).getImageLoader();
Bitmap bm = imageLoader.get(imageUrl, ImageLoader.getImageListener(userImageFragment, android.R.color.white, android.R.color.white)).getBitmap();
userImageFragment.setImageBitmap(bm);
userNameTextFragment.setText(userName);
}
public void loadImagesFromAPI(final String Url) {
loadingLayoutFragment.setVisibility(View.VISIBLE);
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.GET, Url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
ArrayList<Photosphere> photospheres = new ArrayList<>();
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.isNull("userModel") || jsonObject.getJSONObject("userModel").isNull("OtherImages")){
loadingLayoutFragment.setVisibility(View.GONE);
nrOfSpheresFragment.setText("No images");
}
else {
if (userId.length() >0){
LoadUserImage((jsonObject.getJSONObject("userModel")).getString("UserName"),(jsonObject.getJSONObject("userModel")).getString("ImgPath"));
}
photospheres = new WebServiceReader().processSpheresModelJsonData(jsonObject.getJSONObject("userModel"),"OtherImages");
loadingLayoutFragment.setVisibility(View.GONE);
//init adapter
adapter = new PhotosphereListAdapter(getActivity(), photospheres, (userId.length() > 0 ? false : true),true);
listview_spheresFragment.setAdapter(adapter);
nrOfSpheresFragment.setText(nrOfSpheresFragment.getText()+"("+listview_spheresFragment.getCount()+")");
nrOfLikes.setText((jsonObject.getJSONObject("userModel")).getString("TotalLikes"));
nrOfSeens.setText((jsonObject.getJSONObject("userModel")).getString("TotalViews"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
nrOfSpheresFragment.setText("An error occurred. Please try again!");
}
}
);
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
Update!
It seems that all of the fragments are loaded and overwritten in the first tab.
nrOfSpheresFragment.setText(nrOfSpheresFragment.getText()+"("+listview_spheresFragment.getCount()+")");
this line of code updates a textview and I can see that the textview is updated 3 times (25)(10)(5) which means the number of results. Only the last result's listview is visible
I figured out what was the problem.
When I used the fragment, (the fragment was created before, and used in other way) I didn't notice that when I initialize the controls in the page, I use getactivity() instead of rootview. So in order to make it work I changed those two as shown
userImageFragment = (CircleImageView) view.findViewById(R.id.userImageFragment);
userNameTextFragment = (TextView) view.findViewById(R.id.userNameTextFragment);
nrOfSpheresFragment = (TextView) view.findViewById(R.id.nrOfSpheresFragment);
loadingLayoutFragment = (LinearLayout) view.findViewById(R.id.loadingLayoutFragment);
listview_spheresFragment = (ListView) view.findViewById(R.id.listview_spheresFragment);
nrOfLikes = (TextView)view.findViewById(R.id.nrOfLikes);
nrOfSeens = (TextView)view.findViewById(R.id.nrOfSeens);
You can set variable to fragment, witch helps you to choose content you need
private String mUrl; //url of content
//set url of content via newInstanse() method
public static UsersSpheresFragment newInstance(String dataUrl) {
UsersSpheresFragment fragment = new UsersSpheresFragment();
Bundle arguments = new Bundle();
arguments.putInt(EXTRA_KEY_ULR, dataUrl);
fragment.setArguments(arguments);
return fragment;
}
//get url in onCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getArguments();
if (extras == null || !extras.containsKey(EXTRA_KEY_URL))
throw new IllegalArgumentException("missing authorId argument");
mUrl = extras.getInt(EXTRA_KEY_URL);
//load your data
webService.loadData(mUrl);
}
another variant is set type of content via newIntanse(int type) method and choose data match it type in fragment#onCreate()
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.
I am trying to use FragmentStatePagerAdapter with ViewPager to achieve a sequential slide scroll view (similar to most pdf readers). However, while running the code, the following is happening:
When the activity becomes visible, the first page is instantiated with a different (2nd) page's value. However, when scrolled to some other page and then back to page 1, the page displays default text from layout file.
Only 2nd and 2nd to last pages instantiate with the passed value (that too with values from other pages, not their own). Rest of the pages display default text from layout file.
On debugging, I noticed that the index/currentItemNumber changes when ViewPager.populate() calls ViewPager.addNewItem(). Ever more strange is the fact that setText() is called on the TextView (part of fragment layout), but text does not change from the default text.
Am I missing something?
Here is the code below:
MainActivity.java
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private ViewPager mPager;
private Button mButtonFirst;
private Button mButtonPrev;
private Button mButtonGoTo;
private Button mButtonNext;
private Button mButtonLast;
private TextView mPageCount;
private EditText mPageNumber;
private TextView mError;
private int mNumScreens;
private int mCurrScreen;
private MyPagerAdapter mMyPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpViews();
setUpListeners();
setUpPager();
}
private void setUpViews() {
mPager = (ViewPager) findViewById(R.id.my_pager);
// Get other view handles...
mError = (TextView) findViewById(R.id.error_details);
}
private void setUpListeners() {
// Set this class as click handler for all buttons
}
private void setUpPager() {
String[] strings = new String[] {
"1",
"2",
"3",
"4",
"5",
"6"
};
// Success!
// Set adapter and update views
mMyPagerAdapter = new MyPagerAdapter(getSupportFragmentManager(), strings);
mPager.setAdapter(mMyPagerAdapter);
mNumScreens = strings.length;
mPageCount.setText("/" + Integer.toString(mNumScreens));
mCurrScreen = -1;
GoToScreen(1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// Handle options
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button_first:
GoToScreen(1);
break;
case R.id.button_prev:
GoToScreen(mCurrScreen - 1);
break;
case R.id.button_goto:
{
int screen;
boolean reset = false;
try {
screen = Integer.parseInt(mPageNumber.getText().toString());
reset = !SetToScreen(screen);
} catch (NumberFormatException e) {
e.printStackTrace();
reset = true;
}
if(reset) {
mPageNumber.setText(Integer.toString(mCurrScreen));
}
}
break;
case R.id.button_next:
GoToScreen(mCurrScreen + 1);
break;
case R.id.button_last:
GoToScreen(mNumScreens);
break;
}
}
private void GoToScreen(int screen) {
if(SetToScreen(screen)) {
mPageNumber.setText(Integer.toString(mCurrScreen));
}
}
private boolean SetToScreen(int screen) {
// Switch to a valid screen
if(screen >= 1 && screen <= mNumScreens && mCurrScreen != screen) {
mPager.setCurrentItem(screen - 1, false);
// Handle button visibility
// Update current screen
mCurrScreen = screen;
return true;
}
return false;
}
MyPagerAdapter.java
public class MyPagerAdapter extends FragmentStatePagerAdapter {
private final String[] mStrings;
public MyPagerAdapter(FragmentManager fm, String[] strings) {
super(fm);
mStrings = strings;
}
#Override
public int getCount() {
return mStrings.length;
}
#Override
public Fragment getItem(int position) {
return ScreenFragment.newInstance(mStrings[position]);
}
}
ScreenFragment.java
public class ScreenFragment extends Fragment {
private static final String ARG_SCREEN_STRING= "screen_string";
private String mScreenInfo;
private TextView mStatementLabel;
public static ScreenFragment newInstance(String screenString) {
ScreenFragment fragment = new ScreenFragment();
Bundle args = new Bundle();
args.putString(ARG_SCREEN_STRING, screenString);
fragment.setArguments(args);
return fragment;
}
public ScreenFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mScreenInfo = getArguments().getString(ARG_SCREEN_STRING);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_screen, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setUpViews();
setUpFields();
}
private void setUpFields() {
mStatementLabel.setText(mScreenInfo);
}
private void setUpViews() {
mStatementLabel = (TextView) getActivity().findViewById(R.id.qnr_screen_statement);
}
}
The problem was solved when I moved calls to setUpViews() and setUpFields() to onCreateView() from onActivityCreated(), with little modifications. This is how the new onCreateView() looks like (I moved the content of the above mentioned functions here)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_screen, container, false);
mStatementLabel = (TextView) v.findViewById(R.id.qnr_screen_statement);
mStatementLabel.setText(mScreenInfo);
return v;
}
I am yet to figure out why that was causing the problem. Will update if I find anything.
So I have disabled scrolling on my map but at the same time, when I try to scroll left and right to swap the page in the ViewPager, the swipe is not recognized in the ViewPager as I think it still thinks that I am trying to scroll the map. How can I acomplish that?
public class VenueDetailsActivity extends SherlockFragmentActivity{
private static final String[] CONTENT = new String[] { "Camera", "Description", "Menu", "Contact", "Specials" };
private Venue venue;
private CameraFragment camera = null;
private ContactFragment contact = null;
private DescriptionFragment desc = null;
private MenuFragment menu = null;
private SpecialsFragment specials = null;
private ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.venue_details);
initialize();
}
private void initialize(){
actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setHomeButtonEnabled(true);
Intent intent = getIntent();
Bundle b = getIntent().getExtras();
//get the Venue that was passed.
venue = (Venue) b.getParcelable("venue");
actionBar.setTitle(venue.getName());
//create a fragment adapter object
FragmentPagerAdapter adapter = new MyAdapter(getSupportFragmentManager());
//find the viewpager in the view venue_details
ViewPager pager = (ViewPager)findViewById(R.id.pager);
//set the pager to keep total length of Content windows -1 screen fragments( this helps to not redraw the cameras every time you move thrugh tabs )
pager.setOffscreenPageLimit(CONTENT.length-1);
//set adapter for the pager.
pager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator)findViewById(R.id.indicator);
indicator.setViewPager(pager);
}
/* This method handles the each click on the drawable menu */
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
finish();
default:
return super.onOptionsItemSelected(item);
}
}
/* Adapter CLASS to help with fragments */
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
int var = position % CONTENT.length;
switch(var){
case 0:
//check to see if there is an instance already
if(camera == null){
camera = CameraFragment.newInstance(venue);
}
return camera;
case 1:
if(desc==null){
desc = DescriptionFragment.newInstance(venue);
}
return desc;
case 2:
if(menu == null){
menu = MenuFragment.newInstance(venue);
}
return menu;
case 3:
if(contact == null){
contact = ContactFragment.newInstance(venue);
}
return contact;
case 4:
if(specials == null){
specials = SpecialsFragment.newInstance(venue);
}
return specials;
}
return CameraFragment.newInstance(venue);
}
#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position % CONTENT.length].toUpperCase();
}
#Override
public int getCount() {
return CONTENT.length;
}
}
}
This is the one fragment that I want to make sure that even swiping on the map will change my fragments.
public class ContactFragment extends Fragment{
private static final String KEY_CONTENT = "ContactFragment:Content";
private SupportMapFragment fragment;
private GoogleMap map;
private LatLng venueLatLng ;
private static Venue venue;
public static ContactFragment newInstance(Venue venuePassed) {
ContactFragment fragment = new ContactFragment();
venue = venuePassed;
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//create a LatLng object used to send coordinates to Google Maps
venueLatLng = new LatLng(venue.getLocationCoordinates().getLatitude(), venue.getLocationCoordinates().getLongitude());
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//get the child fragment manager
FragmentManager fm = getChildFragmentManager();
//find google maps's fragment that is inserted in the xml
fragment = (SupportMapFragment) fm.findFragmentById(R.id.map);
if (fragment == null) {
//create a new instance of the support fragment
fragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map, fragment).commit();
}
}
#Override
public void onResume() {
super.onResume();
if (map == null) {
map = fragment.getMap();
Marker venueMarker = map.addMarker(new MarkerOptions().position(venueLatLng)
.title(venue.getName())
.snippet("Kiel is cool")
.draggable(false));
venueMarker.showInfoWindow();
map.moveCamera(CameraUpdateFactory.newLatLngZoom(venueLatLng, 15));
map.getUiSettings().setScrollGesturesEnabled(false);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.contact,
container, false);
TextView contact_text = (TextView)view.findViewById(R.id.contact_text);
contact_text.setText(venue.getAddress());
TextView phone_number = (TextView)view.findViewById(R.id.phone_number);
phone_number.setText(venue.getPhoneNumber());
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);;
}
}
If you don't want anything inside the ViewPager to be clickable, try subclassing ViewPager. Override dispatchTouchEvent(MotionEvent e), and return false from it to prevent touch events from being claimed by the ViewPager's children.
I think the source of your problems comes from they way you are loading the SupportMapFragment. You should extend SupportMapFragment instead of Fragment and customize the Map like you do in onResume().
I'm trying to implement an activity with tabs in action bar and a view pager. I have the same fragment for every tab.
I need to update fragments after onCreateView is called, passing objects.
Pager adapter :
public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter() {
super(getSupportFragmentManager());
}
#Override
public int getCount() {
return cat_pages.getList_categories().size();
}
#Override
public Fragment getItem(int position) {
Log.i("position fragment", "i = " + position);
final Handler uiHandler = new Handler();
int index = position;
final Category cat = cat_pages.getList_categories().get(index);
Log.i("position fragment", "name = " + cat.getName());
mCategoriesFragment = new ListPostFragment();
return mCategoriesFragment;
}
}
Fragment :
public class ListPostFragment extends Fragment {
// Layouts
private LinearLayout layout_loading;
public static GridView list_view_articles;
private TextView txt_nothing, txt_title;
// The list of headlines that we are displaying
private List<Post> mPostsList = new ArrayList<Post>();
private List<Post> list_posts = new ArrayList<Post>();
// The list adapter for the list we are displaying
private ArticlesAdapter mListAdapter;
private Category mCurrentCat;
Category clicked_cat;
String activity;
String title;
public ListPostFragment() {
super();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mListAdapter = new ArticlesAdapter(getActivity(), mPostsList);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_grid_posts, container, false);
layout_loading = (LinearLayout) rootView.findViewById(R.id.layout_loading);
list_view_articles = (GridView) rootView.findViewById(R.id.gridViewArticles);
txt_nothing = (TextView) rootView.findViewById(R.id.txt_no_result);
txt_title = (TextView) rootView.findViewById(R.id.txt_title);
Log.i("frag", "frag create view");
return rootView;
}
#Override
public void onStart() {
super.onStart();
list_view_articles.setAdapter(mListAdapter);
}
public void loadPosts(Category clicked_cat, List<Post> list_posts, String title) {
Log.i("frag", "frag load");
layout_loading.setVisibility(View.VISIBLE);
list_view_articles.setVisibility(View.GONE);
txt_title.setVisibility(View.GONE);
mPostsList.clear();
layout_loading.setVisibility(View.GONE);
if(list_posts != null){
mPostsList.addAll(list_posts);
if(mPostsList.size() > 0){
list_view_articles.setVisibility(View.VISIBLE);
txt_nothing.setVisibility(View.GONE);
}else{
list_view_articles.setVisibility(View.GONE);
txt_nothing.setVisibility(View.VISIBLE);
}
mListAdapter.notifyDataSetChanged();
}else{ // Nothing to display
list_view_articles.setVisibility(View.GONE);
txt_nothing.setVisibility(View.VISIBLE);
}
}
}
==> What I need to to call loadPosts(...) in PagerAdapter getItem(), once onCreateView has been called.
Any help is very appreciated.
You should pass your Category as an Extra to the fragment like so:
Bundle bundle = new Bundle();
bundle.putSerializable("CATEGORY", cat);
mCategoriesFragment.setArguments(bundle);
and then in onCreate() in the fragment you can read it using:
Bundle bundle = this.getArguments();
Category cat = (Category) bundle.getSerializable("CATEGORY");
// now you can call loadPosts()