My fragmentClass get wrong page from ViewPager in medod onContextItemSelected - java

First. Sorry for my English.
I have Activity class with ViewPager as a field and a Fragment class. My activity is a host for a fragment. In Fragment I want to call context menu registered for ImageView. For that, I override 2 methods: onCreateContextMenu and onContextItemSelected.
Problem is:
When onCreateContextMenu is called I get the correct page (that
on the screen now).
But when onContextItemSelected is called I get another page (this
depend on what parameter is set in
ViewPager.setOffscreenPageLimit(int)). For example, if it set 3, the returned page will be those, that on 3 positions to the left or to the right from current that on the screen.
How can I fix it?
Thank you.
Activity code
public class CrimePagerActivity extends FragmentActivity {
private ViewPager mViewPager;
private ArrayList<Crime> mCrimes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.viewPager);
setContentView(mViewPager);
mCrimes = CrimeLab.get(this).getCrimes();
mViewPager.setOffscreenPageLimit(4);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mViewPager.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
FragmentManager fm = getSupportFragmentManager();
mViewPager.setAdapter(new FragmentStatePagerAdapter(fm) {
#Override
public Fragment getItem(int position) {
Crime crime = mCrimes.get(position);
return CrimeFragment.newInstance(crime.getId());
}
#Override
public int getCount() {
return mCrimes.size();
}
});
UUID crimeId = (UUID) getIntent().getSerializableExtra(CrimeFragment.EXTRA_CRIME_ID);
for (int i = 0; i< mCrimes.size(); i++){
if (mCrimes.get(i).getId().equals(crimeId)){
mViewPager.setCurrentItem(i);
break;
}
}
}
}
and fragment code
public class CrimeFragment extends Fragment {
.......
private ImageView mPhotoView;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
........
View v = inflater.inflate(R.layout.fragment_crime, container, false);
mPhotoView = (ImageView) v.findViewById(R.id.crime_imageView);
registerForContextMenu(mPhotoView);
return v;
}
.........
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
Log.i(TAG, mCrime.getTitle());
switch (v.getId()) {
case R.id.crime_imageView:
if (mCrime.getPhoto() != null)
getActivity().getMenuInflater().inflate(R.menu.crime_photo_context, menu);
break;
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
Log.i(TAG, mCrime.getTitle());
switch (item.getItemId()) {
case R.id.menu_item_delete_photo:
getActivity().deleteFile(mCrime.getPhoto().getFilename());
PictureUtils.cleanImageView(mPhotoView);
mCrime.setPhoto(null);
return true;
}
return super.onContextItemSelected(item);
}
}

ViewPager.setOffscreenPageLimit(int);
This will prepare the pages at both sides to the left and right (neighbours).
By default it is 1.
So, in your case to get the current fragment created by the viewPager.
You can store the fragments when created in an SparseArray by overriding the instantiateItem() and destroyItem() callback of viewPager with position.
private SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
#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 getFragment(int position) {
return registeredFragments.get(position);
}
And where you want to get the current fragment, get it by using the getFragment() method by passing the position.

Related

Viewpager Fragment 1 onCreateView is not always being called

When I swipe to or select Fragment1 (Fragment Numbers are 0-3) from its adjacent Fragments(0 , 2) in viewPager its onCreateView, or onCreate function is not being called.
But when I swipe back from Fragment3 or select Fragment1 when Fragment3 is active then both of these functions are being called. I am confused about why not from the adjacent Fragments its being called.
this is the code of Fragment who's onCreateView is not being called properly
`public class Fragment1 extends Fragment {
ShimmerFrameLayout shimmerFrameLayout ;
ConstraintLayout contentLayout;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(getActivity(), "US News", Toast.LENGTH_SHORT).show();
Log.d("Called", "onCreate: ");
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.us_news_fragment_layout , container , false);
shimmerFrameLayout = view.findViewById(R.id.usNewsShimmerLayoutId);
contentLayout = view.findViewById(R.id.usNewsLayoutId);
shimmerFrameLayout.startShimmerAnimation();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
shimmerFrameLayout.stopShimmerAnimation();
shimmerFrameLayout.setVisibility(View.GONE);
contentLayout.setVisibility(View.VISIBLE);
}
},3000);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d("USNews", "onCreateView: ");
}
}`
This is the code in the main Activity for handling the events related to the viewpager
viewPager = findViewById(R.id.homeViewPagerId);
tabLayout.setupWithViewPager(viewPager);
tabLayout.addTab(tabLayout.newTab().setText("Home"));
tabLayout.addTab(tabLayout.newTab().setText("US News"));
tabLayout.addTab(tabLayout.newTab().setText("Politics"));
tabLayout.addTab(tabLayout.newTab().setText("Live"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
viewPager.setCurrentItem(position);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
homePagerAdapter = new HomePagerAdapter(getSupportFragmentManager() , tabLayout.getTabCount());
viewPager.setAdapter(homePagerAdapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// Toast.makeText(MainActivity.this, String.valueOf(tabLayout.getTabAt(position).getText()) + " is Active Now", Toast.LENGTH_SHORT).show();
homePagerAdapter.getItem(position);
}
#Override
public void onPageSelected(int position) {
homePagerAdapter.getItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
homePagerAdapter.notifyDataSetChanged();
And this is the adapter of the ViewPager i am using
public class HomePagerAdapter extends FragmentStatePagerAdapter {
int NUM_OF_TABS;
private String[] tabTitles = new String[]{"Home", "US News", "Politics" , "Live"};
public HomePagerAdapter(#NonNull FragmentManager fm , int numberOfTabs) {
super(fm);
this.NUM_OF_TABS = numberOfTabs;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Fragment0 homeFragment = new Fragment0 ();
return homeFragment;
case 1:
Fragment1 usNewsFragment = new Fragment1 ();
return usNewsFragment;
case 2:
Fragment2 politicsFragment = new Fragment2 ();
return politicsFragment;
case 3:
Fragment3 liveFragment = new Fragment3 ();
return liveFragment;
default:
return null;
}
}
#Override
public int getCount() {
return NUM_OF_TABS;
}
}
Please assist me about this. I'll be very thankful to you.
Thanks in advance
maybe this layout is already created and drawn? ViewPager have some handy option - keeps at least two additional Views/Fragments in memory for fast switching between pages. you can change this value to some higher only by calling setOffscreenPageLimit. by default its set to 1 - means that ViewPager keeps up to 3 Fragments - one to the left, one to the right and one currently visible on screen. with finger fling UI can just slide left/right page without drawing it from scratch (making almost always some small glitch/hang)
I bet you have two onCreate calls on start of your Activity - Fragment0s and Fragment1s. when you switch to Fragment1 you will see Fragment2 log, as ViewPager will prepare it for potential next swipe-left gesture. you can always use setOffscreenPageLimit(Integer.MAX_VALUE); for forcing all Fragments to be drawn at start and kept in memory (but only if these Fragments aren't to heavy, according to your tab names they might be...)
also homePagerAdapter.getItem(position); call in onPageSelected and onPageScrolled is unnecessary - it is creating new Frament and returning it, thats all, it isn't used. thats ViewPagers job to call this method (from attached adapter), take this Fragment and draw (on the screen or just render in memory for potential future use when user swipe left/right)

OnClick Fragment to Fragment switch results in Blank Screen

When switching from one fragment to another fragment (within the second tab of my application), my second fragment is blank. I have tried the solutions linked here, but none seem to work:
Transaction of fragments in android results in blank screen
Android: Getting white screen with fragment transaction
MainActivity:
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter, and add pages.
mViewPager = (ViewPager) findViewById(R.id.container);
mSectionsPagerAdapter.addPage(new Received());
mSectionsPagerAdapter.addPage(new Send());
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#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_alert_partners, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
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() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(getArguments().getInt(ARG_SECTION_NUMBER)==1) {
View rootView = inflater.inflate(R.layout.fragment_received, container, false);
return rootView;
}
else if(getArguments().getInt(ARG_SECTION_NUMBER)==2) {
View rootView = inflater.inflate(R.layout.fragment_send, container, false);
return rootView;
}
else {//main empty fragment in case of error. Never used in normal behaviour.
View rootView = inflater.inflate(R.layout.fragment_alert_partners, container, false);
return rootView;
}
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
//Create an Array list that will hold the pages.
ArrayList<Fragment> pages = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
return pages.get(position);
}
//Add a page
public void addPage(Fragment f) {
pages.add(f);
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Received";
case 1:
return "Send";
}
return null;
}
}
}
SendFragment:
public class Send extends Fragment {
private OnFragmentInteractionListener mListener;
private TextView text1;
public Send() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_send, container, false);
//Need getView() for fragment since setContentView must be set first but is not possible in fragment.
text1 = (TextView)v.findViewById(R.id.textview1);
text1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Send2 send2 = new Send2();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.hide(Send.this);
fragmentTransaction.add(android.R.id.content, send2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
return v;
}
public interface OnFragmentInteractionListener {
}
}
Send2Fragment:
public class Send2 extends Fragment {
private OnFragmentInteractionListener mListener;
public Send2() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View v = inflater.inflate(R.layout.fragment_send2, container, false);
return v;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
}
}
Had to add a framelayout at the end of the layout code for the fragment I was replacing:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/send1frameLayoutId">
</FrameLayout>
Then used this code to switch to a fragment in the same tab of the previous fragment:
Fragment send2 = new Send2();
FragmentManager fragmentManager = getChildFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.send1frameLayoutId, send2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

NullPointerException when I call method of interface (fragments communication) [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
My app works with a TabLayout (and so a ViewPager).
I have a Fragment A and a Fragment B. My goal is to recover data from my EditTexts of Fragment A to, obviously, print and works with them in my Fragment B.
For this, I use an interface named ButtonCliked, but seems not to work well. Did I forgot something ?
TabFragment.java (use to manage my fragments)
public class TabFragment extends Fragment implements EquationsCalculFragment.ButtonClicked {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3 ;
#Override
public void sendResultats(float a, float b) {
EquationsResultatFragment fragRes = (EquationsResultatFragment) getFragmentManager().findFragmentById(R.id.Equa_2nd_ResLayout);
fragRes.getResultat(a, b);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.tab_layout,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new EquationsCalculFragment();
case 1 : return new EquationsResultatFragment();
case 2 : return new EquationsInfosFragment();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "Calcul";
case 1 :
return "Résultats";
case 2 :
return "Infos";
}
return null;
}
}
}
Fragment A : EquationsCalculFragment.java
public class EquationsCalculFragment extends Fragment {
private String aS;
private String bS;
private EquationsCalculFragment.ButtonClicked callEqua2ndRes;
public interface ButtonClicked {
void sendResultats(float a, float b);
}
private ViewPager viewPager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_equations_calcul, container, false);
viewPager = (ViewPager) getActivity().findViewById(R.id.viewpager);
final EditText champ_a = (EditText) view.findViewById(R.id.equa_2nd_a);
final EditText champ_b = (EditText) view.findViewById(R.id.equa_2nd_b);
Button button = (Button) view.findViewById(R.id.btn_equations_resultats);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bS = champ_b.getText().toString();
aS = champ_a.getText().toString();
callEqua2ndRes.sendResultats(Float.parseFloat(aS), Float.parseFloat(bS));
viewPager.setCurrentItem(1, true);
}
});
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
if (context instanceof EquationsCalculFragment.ButtonClicked) {
callEqua2ndRes = (EquationsCalculFragment.ButtonClicked) context;
}
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement ButtonClicked");
}
}
#Override
public void onDetach() {
callEqua2ndRes = null;
super.onDetach();
}
}
Fragment B : EquationsResultatFragment.java
public class EquationsResultatFragment extends Fragment {
private TextView results;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_equations_resultat, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
results = (TextView) getView().findViewById(R.id.equa_2nd_resultat);
}
public void getResultat(float a, float b) {
results.setText(String.valueOf((a*a)+(2*a*b)+(b*b)));
}
}
Is there anything I'm doing wrong ?
I thinkthe NPE is because you try to find the fragment with it's id, but you supply I guess the id of the ViewPager? Try finding it by tag, it should look something like this:
int position;
getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.yourViewPagerIdGoesHere + ":" + position);
Where the position is the pos of your targeted fragment just like in the adapter's public Fragment getItem(int position) method
Issue is you have declared an interface in EquationsCalculFragment but never initialied it :)
So here is what you can do :)
In EquationsCalculFragment, change
private EquationsCalculFragment.ButtonClicked callEqua2ndRes;
to
public EquationsCalculFragment.ButtonClicked callEqua2ndRes;
and in TabFragment, getItem methods case 0, make this change :)
case 0 : EquationsCalculFragment calculationFragment = new EquationsCalculFragment();
calculationFragment.callEqua2ndRes = TabFragment.this;
return calculationFragment;
Should solve your issue :) Hope my answer helped :)
P.S : Code provided above is to explain the concept and not for copy paste, might contain syntactic error :) If contains please modify and use it :D

Add fragment into viewPager's fragment

I have viewpager with 3 fragments (same layout - some EditText and Buttons) and I want to dynamically add small fragment above the viewpager fragment, write something in and then hide it.
This is what I tried:
MainActivity.java:
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return MainFragment.newInstance("1");
case 1: return MainFragment.newInstance("2");
case 2: return MainFragment.newInstance("3");
default: return MainFragment.newInstance("");
}
}
#Override
public int getCount() {
return 3;
}
}
}
MainFragment.java:
public class MainFragment extends android.support.v4.app.Fragment {
EditText contentEdit;
String content, ID;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ID = getArguments().getString("msg");
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
contentEdit = (EditText) view.findViewById(R.id.editText);
contentEdit.setOnTouchListener(new OnSwipeTouchListener(getActivity()) {
public void onSwipeBottom() {
final ViewGroup newView = (ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.fragment_title, container, false);
newView.findViewById(R.id.delete_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
container.removeView(newView);
}
});
container.addView(newView, 0);
}
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
});
return view;
}
}
Try to put a frame layout above that viewPager layout BUT set it's visibility to GONE therefore it won't "exist". Now in your pager onItemClick listener for that small fragment you want to show call findViewByID(R.id.YourFrameLayout).setVisibility(View.VISIBLE); and when you want to hide it, well you get the idea. Don't forget to add your fragment to that container, e.g. YourFrameLayout

Pass parameters between viewpager fragments

I have an activity that holds 2 fragments, one for list and one for detail. What I would like to do is, whenever a list item is clicked the related parameters will be sent to detail fragment. But I couldn't achieve it.
Here is activity:
public class ActivityMain extends ActionBarActivity{
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
List<String> naviList = new ArrayList<String>();
ViewPager mViewPager;
private ActionBarDrawerToggle drawerToggle;
private DrawerLayout drawer;
ListView navList;
DrawerAdapter naviAdapter;
private static final int GRAVITY = Gravity.LEFT;
private static final String jsonURL = "";
List<String> categories = new ArrayList<String>();
int check = -1, listCheck = 0;
Dialog d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 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.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
//some methods (e.g. navi-drawer etc.)
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.medicalendar_main, 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.
switch (item.getItemId()) {
case R.id.action_settings:
return true;
}
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return ListFragment.newInstance("FirstFragment, Default");
case 1:
return DetailFragment.newInstance("DetailFragment, Detail");
default:
return ListFragment.newInstance("FirstFragment, Default");
}
}
#Override
public int getCount() {
return 2;
}
}
private boolean version() {
if (Build.VERSION.SDK_INT > 11) {
return true;
} else {
return false;
}
}
My List Fragment:
public class ListFragment extends Fragment {
ListView list;
LazyAdapter adapter;
List<String> naviList = new ArrayList<String>();
RelativeLayout loading;
EventsParser parser;
List<Event> events = new ArrayList<Event>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_list, container, false);
parser = new EventsParser("");
events = parser.getITEMS();
list = (ListView) v.findViewById(R.id.list);
adapter = new LazyAdapter(getActivity(), events);
list.setAdapter(adapter);
return v;
}
public static ListFragment newInstance(String text) {
ListFragment f = new ListFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ViewPager vp = (ViewPager) getActivity().findViewById(R.id.pager);
//clicked item's data to pass next page.
vp.setCurrentItem(1);
}
});
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
My Detail Fragment:
public class DetailFragment extends Fragment {
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_detail, container, false);
ImageButton imageButton = (ImageButton) v.findViewById(R.id.d_map);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity().getApplicationContext(), "Navigating...", Toast.LENGTH_LONG).show();
}
});
return v;
}
public static DetailFragment newInstance(String text) {
DetailFragment f = new DetailFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
}
If you could help me I would be greatly appriciated.
Best,
Basically you don't need ViewPager for navigating from one fragment to another. This should be achieved with replacing fragments using FragmentTransaction class, that will allow you to pass parameters in transaction. http://developer.android.com/reference/android/app/FragmentTransaction.html
If you still need ViewPager, you should set tag for each fragment with
fragment.setTag("detail_fragment");
and than your onListItemClick method should look like this:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//get detail fragment instance by it's tag
DetailFragment detail = (DetailFragment) getActivity().getFragmentManager().findFragmentByTag("detail_fragment");
detail.setParam("data"); //you should define this method in your detail fragment
ViewPager vp = (ViewPager) getActivity().findViewById(R.id.pager);
//clicked item's data to pass next page.
vp.setCurrentItem(1);
}

Categories