Getting application context into fragment, ViewPager - android

I'm writing a simple app with swipe view using viewpager and fullscreen fragments. In one of fragments I want to check internet connection status before displaying some data but I can't get the application context. I've found a lot of topics on this issue, but none of solutions works for me. I am using getApplication() within fragment but even though I get error "Unreacheable statement".
Any advice?
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
public class MainActivity extends FragmentActivity {
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setting fragment view pager
viewPager = (ViewPager)findViewById(R.id.pager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
}
activity_main.xml
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
First fragment
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class CurrentWeatherFragment extends Fragment {
//flaga dla statusu polaczenia z internetem
Boolean isInternetPresent = false;
//klasa detektora połączenia
ConnectionDetector cd;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.currentweather, container, false);
return v;
//tworzenie klasy detektora
cd = new ConnectionDetector(getActivity().getApplicationContext());
//sprawdzenie czy jest polaczenie z internetem
isInternetPresent = cd.isConnectingToInternet();
}
}
Pager Adapter class
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class PagerAdapter extends FragmentPagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
switch (arg0){
case 0:
return new CurrentWeatherFragment();
case 1:
return new ForecastFragment();
default:
break;
}
return null;
}
#Override
public int getCount() {
return 2;
}
}

In the CurrentWeatherFragment's onCreateView you inflate the View then instantly return it.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.currentweather, container, false);
return v;
//tworzenie klasy detektora
cd = new ConnectionDetector(getActivity().getApplicationContext());
//sprawdzenie czy jest polaczenie z internetem
isInternetPresent = cd.isConnectingToInternet();
}
Move the return v; to the end of the method:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.currentweather, container, false);
//tworzenie klasy detektora
cd = new ConnectionDetector(getActivity().getApplicationContext());
//sprawdzenie czy jest polaczenie z internetem
isInternetPresent = cd.isConnectingToInternet();
return v;
}

Could be a lifecycle problem. Make that call in onAttach(Activity) instead of in onCreateView()

Related

ViewHolder views must not be attached when created. Ensure that you are not passing 'true' to the attachToRoot parameter of LayoutInflater.inflate?

I need some help with this issue. Sunddenly I'm getting this error. I did no modifications and can't find a solution... here goes a piece of the error.
java.lang.IllegalStateException: ViewHolder views must not be attached when created. Ensure that you are not passing 'true' to the
attachToRoot parameter of LayoutInflater.inflate(..., boolean
attachToRoot)
at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6687)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5869)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5752)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5748)
at com.beloo.widget.chipslayoutmanager.ChipsLayoutManager.layoutDisappearingViews(ChipsLayoutManager.java:767)
at com.beloo.widget.chipslayoutmanager.ChipsLayoutManager.onLayoutChildren(ChipsLayoutManager.java:731)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3812)
at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3225)
at android.view.View.measure(View.java:19759)
package com.example.xandi.amicer;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionPagerAdapter mSectionsPagerAdapter = new SectionPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
ViewPager mViewPager = findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_tab_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
Here is the class I suppose that is causing this error
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_edit_profile, container, false);
Try this :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_edit_profile, container, true);
}

android- implementing ListVIew in Fragment using Base adapter , what am i doing wrong?

Problem Sloverd, i was trying to implement listview in a fragment without implenting listfragment
(just extends fragment)
and A custom adapter without extending any ArrayAdapter or ListAdapter..
(just extends BaseAdapter)
My following code is showing no error but listview is not showing in the fragment. I am using a custom adapter to show two edittext together. during debugging i can see adapter sending a list in the view but listview.setadapter() not binding any data Can anyone tell me what i am doing wrong? i have tried to find similar solution here but no luck. I would greatly appreciate any feedback or pointing to a similar problem like this . Fragment:
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class ResultFragment extends Fragment {
private DBHelper dbHelper=null;
ArrayList<MedicineModel> medicineModelList=new ArrayList<MedicineModel>();
String selectedData="";
CustomAdapterBrandResult adapter;
ListView listView;
public ResultFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_result, container, false);
listView= (ListView) view.findViewById(R.id.resultList);
TextView textView=(TextView)view.findViewById(R.id.selected_text);
Bundle bundle=getArguments();
if(bundle!=null){
textView.setText(bundle.getString("selected_data"));
selectedData=(bundle.getString("selected_data"));
}
dbHelper=new DBHelper(this.getActivity());
medicineModelList= dbHelper.getAllUsingBrandName(selectedData);
adapter=new CustomAdapterBrandResult(getActivity(), medicineModelList);
listView.setAdapter(adapter);
return view;
}
}
Custom Adapter
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapterBrandResult extends BaseAdapter {
private Context mcontext;
private ArrayList<MedicineModel> medicineModelList;
public CustomAdapterBrandResult(Context mcontext, ArrayList<MedicineModel> medicineModelList) {
this.mcontext = mcontext;
this.medicineModelList = medicineModelList;
}
#Override
public int getCount() {
return medicineModelList.size();
}
#Override
public Object getItem(int position) {
return medicineModelList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view=View.inflate(mcontext,R.layout.custom_layout_brand_result,null);
final TextView textViewBrand=(TextView)view.findViewById(R.id.textView2BrandName);
final TextView textViewManufacture=(TextView)view.findViewById(R.id.textView3Manufacture);
textViewBrand.setText( medicineModelList.get(position).getBrandName());
textViewManufacture.setText(medicineModelList.get(position).getNameoftheManufacturer());
return view;
}
}
Finally! able to show the listview in my fragment.Added override onCreate method and intialized list and adpater there and in the override onCreateView method just set the adapter on the listview,that is it..working per perfactly fine. Thanks to the guys ,
#IntelliJAmiya and
#Mikerizzo
who comment on my question and spent their time to examine it
Here is the final solution : Fragment
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle=getArguments();
if(bundle!=null){
selectedData=(bundle.getString("selected_data"));
}
dbHelper=new DBHelper(this.getActivity());
medicineModelList= dbHelper.getAllUsingBrandName(selectedData);
adapter=new CustomAdapterBrandResult(getActivity(), medicineModelList);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_result, container, false);
listView= (ListView) view.findViewById(R.id.resultList);
TextView textView=(TextView)view.findViewById(R.id.selected_text);
textView.setText(selectedData);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
// int a = listView.getAdapter().getCount();
return view;
}

java.lang.IllegalStateException: The specified child already has a parent Only while Using FadingActionBar library?

https://github.com/ManuelPeinado/FadingActionBar I am using this library to implement fading action bar in my fragment.(starts with a navigation drawer[Main Activity] , and
on click of one item in nav drawer it opens main content. A list fragment[Fragment 1]
and on click on any item in list it opens another fragment which displays details
[Fragment 2] ) .
I click on item on nav drawer and then in 1st frag click on any list item and then it open 2 nd frag.Now
My apps crashes when i click back button when on 2nd Fragment.with error
java.lang.IllegalStateException: The specified child already has a parent.You must call removeView() on the child's parent first.
if in 1 st fragment i use in onCreateView
return inflater.inflate(R.layout.myxml,container,false);
It DOES NOT CRASH
BUT if i use (below in OncreateView along with onAttach) as i have to implement fadingActionbarlibrary : IT CRASHES.
oncreateView(....){
super...
view = mFadingHelper.createView(inflater);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mFadingHelper = new FadingActionBarHelper()
.actionBarBackground(R.drawable.ab_background)
.headerLayout(R.layout.header_light)
.contentLayout(R.layout.list_main_all)
.lightActionBar(true);
mFadingHelper.initActionBar(activity);
}
1 st FTRAG
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;
import android.support.v4.app.ListFragment;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.manuelpeinado.fadingactionbar.FadingActionBarHelper;
public class CommunityFragment extends ListFragment {
View view;
private FadingActionBarHelper mFadingHelper;
List<list_object> lite = new FlowerData().getFlowers();
public CommunityFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
list_all_main_adapter adap = new list_all_main_adapter(getActivity(),
R.layout.list_view_custom_all, lite);
setListAdapter(adap);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
list_click fragment = null;
switch (position) {
case 0:
getFragmentManager().beginTransaction()
.replace(getId(), new list_click(position), "Passing and replacing")
.addToBackStack(null).commit();
// getFragmentManager().beginTransaction().remove(new CommunityFragment()).commit();
break;
case 1:
getFragmentManager().beginTransaction()
.replace(getId(), new list_click(position), "Passing and replacing")
.addToBackStack(null)
.commit();
break;
case 2:
getFragmentManager().beginTransaction()
.replace(getId(), new list_click(position), "Passing and replacing")
.commit();
break;
default:
break;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = mFadingHelper.createView(inflater);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mFadingHelper = new FadingActionBarHelper()
.actionBarBackground(R.drawable.ab_background)
.headerLayout(R.layout.header_light)
.contentLayout(R.layout.list_main_all)
.lightActionBar(true);
mFadingHelper.initActionBar(activity);
}
}
2nd Fragment
import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.manuelpeinado.fadingactionbar.FadingActionBarHelper;
public class list_click extends Fragment {
public static int pos = 0;
View v;
public list_click() {
}
public list_click(int p) {
pos = p;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.onlist_clik, container, false);
TextView tv = (TextView) v.findViewById(R.id.textView3);
tv.setText("Position " + pos);
return v;
}
}
Thanks.
I encountered the same issue and found the following workaround:
I think this is a fool proof way to avoid re-inflating of the root view of the fragment:
private WeakReference<View> mRootView;
private LayoutInflater mInflater;
/**
* inflate the fragment layout , or use a previous one if already stored <br/>
* WARNING: do not use in any function other than onCreateView
* */
private View inflateRootView() {
View rootView = mRootView == null ? null : mRootView.get();
if (rootView != null) {
final ViewParent parent = rootView.getParent();
if (parent != null && parent instanceof ViewGroup)
((ViewGroup) parent).removeView(rootView);
return rootView;
}
rootView = mFadingHelper.createView(mInflater);
mRootView = new WeakReference<View>(rootView);
return rootView;
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
mInflater=inflater!=null?inflater:LayoutInflater.from(getActivity());
final View view = inflateRootView();
... //update your data on the views if needed
}
if your problem is really solved then please don't forget fit up arrow which describes that the solution is provided shows research efforts; it is useful and clear.

Android - Getting context of a fragment in a pager

I have a android application using a pager as navigation. For the tabs I have 3 layouts as content. On one of the fragments is a gallery and I want to add images to it. For that I have to set an ImageAdapter but I need to know how to access the context of a fragment.
final LayoutInflater factory = getLayoutInflater();
final View view = factory.inflate(R.layout.pictures, null);
Gallery g = (Gallery) view.findViewById(R.id.gallery1);
g.setAdapter(new ImageAdapter(view.getContext()));
I use this code above in the onCreate method to get the gallery from a layout that is not the contentview.
I have to give a Context to the ImageAdapter. But what context do I have to set there?
EDIT: This is my complete code:
package com.bw2801.uwelugemediathek;
import java.util.Locale;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Context;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.SpinnerAdapter;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
PicturesSectionFragment ps = new PicturesSectionFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
final LayoutInflater factory = getLayoutInflater();
final View view = factory.inflate(R.layout.pictures, null);
Gallery g = (Gallery) view.findViewById(R.id.gallery1);
g.setAdapter(new ImageAdapter(ps.getActivity()));
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private Integer[] mImageIds = {
R.drawable.image01,
R.drawable.image02,
R.drawable.image03,
R.drawable.image04,
R.drawable.image05,
R.drawable.image06,
R.drawable.image07,
R.drawable.image08,
};
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mImageIds[position]);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
return i;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* 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 new DummySectionFragment();
case 1:
return new SoundSectionFragment();
case 2:
return ps;
}
return new DummySectionFragment();
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Informationen";
case 1:
return "Soundboard";
case 2:
return "Galerie";
}
return null;
}
}
public static class DummySectionFragment extends Fragment {
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.info, container, false);
}
}
public static class PicturesSectionFragment extends Fragment {
public PicturesSectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.pictures, container, false);
}
}
public static class SoundSectionFragment extends Fragment {
public SoundSectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.sounds, container, false);
}
}
}
Fragments don't have their own Context, they use parent Activity.
To get parent Activity Context, use getActivity()
To use Application Context, use getActivity().getApplicationContext()
Prefer Application Context wherever possible.
UPDATE:
getActivity() of a Fragment returns an Activity instance if and only if, the said Fragment is currently attached to an Activity.
So,
Fragment f = new MyFragment();
creates a fragment, but it is not attached to an activity yet. Hence f.getActivity() returns null.
After its added to an activity:
getFragmentManager().beginTransaction().add(f,"fragment").commit();
Now, getActivity() will return an Activity instance.
Again, if we detach the fragment from Activity:
getFragmentManager().beginTransaction().detach(f).commit()
getActivity() will again return a null value.
So, we should not use getActivity() outside the Fragment class, because we can't be sure of attached status. Thus I'll advice you to used getActivity() inside the fragment's own class in its methods: onAttach(), onCreate() or onActivityCreated().
you can use like this
g.setAdapter(new ImageAdapter(getActivity()));
The easiest and most precise way to get the context of the fragment that I found is to get it directly from the ViewGroup when you call onCreateView method at least here you are sure not to get null for getActivity()
public class Animal extends Fragment {
Context thiscontext;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
thiscontext = container.getContext();
write under code in Your CoreApplication.java
step1)
public class CoreApplication extends Application {
private static CoreApplication instance;
}
step2) onCreate(){
instance = this;
}
step3 )
add under method()
public static CoreApplication getGlobalApplicationContext() {
if (instance == null) {
throw new IllegalStateException("this application does not
inherit GlobalApplication"); " +
"}
return instance;
}
Step4)
g.setAdapter(new ImageAdapter(getGlobalApplicationContext()));

Android swiping, using ViewPager without tabs

Im trying to make an app that have the navigation type of swiping.
This is how far I have gone:
Fragment activity:
package com.app.BoomBase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment_control extends Fragment {
String tag = this.getClass().getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(tag, "onCreate");
super.onCreate(savedInstanceState);
/** Getting the arguments to the Bundle object */
Bundle data = getArguments();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i(tag, "onCreateView");
View view = inflater.inflate(R.layout.fragment_controle,container, false );
return view;
}
}
FragmentPageAdapter:
package com.app.BoomBase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class Fragment_Pager extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
public Fragment_Pager(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int arg0) {
Fragment_control myFragment = new Fragment_control();
Bundle data = new Bundle();
data.putInt("current_page", arg0+1);
myFragment.setArguments(data);
return myFragment;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return PAGE_COUNT;
}
}
MainActivity:
package com.app.BoomBase;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
String tag = this.getClass().getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(tag, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** Getting a reference to the ViewPager defined the layout file */
ViewPager pager = (ViewPager) findViewById(R.id.pager);
/** Getting fragment manager */
FragmentManager fm = getSupportFragmentManager();
/** Instantiating FragmentPagerAdapter */
Fragment_Pager pagerAdapter = new Fragment_Pager(fm);
/** Setting the pagerAdapter to the pager object */
pager.setAdapter(pagerAdapter);
}
}
But my problem is that i can't figure out how to add fragments to the code. I want to swipe to the next activity with buttons and stuff on them. How do I do that ?
PageAdapter uses your getItem() to switch between Fragments, this is where you would declare which page does what. "Position" 0 is the first page, 1 is the second and so forth. You can simply return a new instance of your other Fragments or pass arguments if you wish.
For example:
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
// Your current main fragment showing how to send arguments to fragment
Fragment_control myFragment = new Fragment_control();
Bundle data = new Bundle();
data.putInt("current_page", position+1);
myFragment.setArguments(data);
return myFragment;
case 1:
// Calling a Fragment without sending arguments
return new MySecondFragment();
case 2:
return new MyThirdFragment();
default:
return null;
}
}
Then you would create a Fragment class for each of those you want to incorporate. In my example you would have a class for MySecondFragment and MyThirdFragment
public class MySecondFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.second_fragment, null);
return view;
}
}
And
public class MyThirdFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.third_fragment, null);
return view;
}
}
Any fragment may simply inflate a standard xml layout file, to access the children in the layout you would have to remember to use the following, I'll use MySecondFragment as an example.
Let's say you have two Buttons with id's R.id.button1 and R.id.button2 in a layout file titled 'second_fragment':
public class MySecondFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.second_fragment, null);
// Make sure to add the parent inflater before and layout child call
Button btn_one = (Button)view.findViewById(R.id.button1);
Button btn_two = (Button)view.findViewById(R.id.button2);
return view;
}
}
Edit
To start at a page other then 0 or the first position you would simply use setCurrentItem() in your MainAvticity, like so:
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(tag, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager pager = (ViewPager) findViewById(R.id.pager);
FragmentManager fm = getSupportFragmentManager();
Fragment_Pager pagerAdapter = new Fragment_Pager(fm);
// Here you would declare which page to visit on creation
pager.setAdapter(pagerAdapter);
pager.setCurrentItem(1);
}
I have added this in fragment class ..
the issue i got is cannot resolve cannot resolve get support fragment manager ().
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(tag, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager pager = (ViewPager) findViewById(R.id.pager);
FragmentManager fm = getSupportFragmentManager();
Fragment_Pager pagerAdapter = new Fragment_Pager(fm);
// Here you would declare which page to visit on creation
pager.setAdapter(pagerAdapter);
pager.setCurrentItem(1);
}

Categories

Resources