I have a ViewPager that I want to add Fragments to.
The ViewPager is viewed correctly on the screen but unfortunately it does not hold any content.
I have seen the suggestion in some posts to replace
getSupportFragmentManager()
with
getChildFragmentManager()
But I need the ActionBar. Unfortunately the ChildFragmentmanager is not available in the AppCompatActivity.
While debugging I have realized that the Fragment's onCreateView() method is called and it returns a layout.
Question: How can I make the Fragments visible? And were is the main difference from my code to that sample ?
Activity:
public class ViewPagerActivity extends AppCompatActivity {
private ViewPager mViewPager;
private List<Location> locationList = new ArrayList<>();
private locationsBaseHandler db;
private CustomPagerAdapter mAdapter;
private Location mLocation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewpager);
locationList.add(someData);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
mAdapter = new CustomPagerAdapter(this, getSupportFragmentManager(), locationList);
mViewPager.setAdapter(mAdapter);
}
}
Pager Adapter:
public class CustomPagerAdapter extends FragmentPagerAdapter {
private Context mContext;
private List<Location> locationList = new ArrayList<>();
public CustomPagerAdapter(Context mContext, FragmentManager fm, List<Location> locationList) {
super(fm);
this.locationList.addAll(locationList);
this.mContext = mContext;
}
#Override
public Fragment getItem(int position) {
return LocationFragment.newInstance(position);
}
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
}
Fragment:
public class LocationFragment extends Fragment {
private static final String ARG_LAYOUT_ID = "page_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_location, container, false);
return layout;
}
public static LocationFragment newInstance(int selectedIdForIndex) {
LocationFragment fragment = new LocationFragment();
Bundle args = new Bundle();
args.putInt(ARG_LAYOUT_ID, selectedIdForIndex);
fragment.setArguments(args);
return fragment;
}
public int getPageNumber() {
return getArguments().getInt(ARG_LAYOUT_ID);
}
}
Try to remove the method isViewFromObject in CustomPagerAdapter.
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
We can see this comment to isViewFromObject:
Determines whether a page View is associated with a specific key object
as returned by {#link #instantiateItem(ViewGroup, int)}. This method is
required for a PagerAdapter to function properly.
Related
I want to want to make ViewPager with each tab containing three fragments. FragmentPagerAdapter only works for one fragment, so I tried my best to make my own custom adapter extending PagerAdapter. Unfortunately, the code I wrote only displays these three Fragments in the first tab and after restarting the app all tabs are blank. I suspect that it has something to do with onSaveInstanceState, but I don't know how to make it properly. Also, I've read that I shouldn't add the fragments to FragmentTransaction in instantiateItem, but I don't know where else I could do it. Could you help me ?
TaskListPagerActivity:
public class TaskListPagerActivity extends AppCompatActivity implements BottomPanelFragment.OnBottomPanelSelectedListener {
private static final String TAG = "TaskListPagerActivity";
private ViewPager mViewPager;
FragmentStacker[] mStacker;
public static Intent newInstance(Context packageContext) {
Intent intent = new Intent(packageContext, TaskListPagerActivity.class);
return intent;
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_list_pager);
mStacker = new FragmentStacker[7];
mViewPager = (ViewPager) findViewById(R.id.activity_task_list_pager);
mViewPager.setAdapter(new TaskListPagerAdapter(this));
}
// Interface methods
private class TaskListPagerAdapter extends PagerAdapter {
private FragmentActivity mContext;
public TaskListPagerAdapter(FragmentActivity context) {
mContext = context;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment res;
FragmentManager fm = mContext.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
if (mStacker[position] == null) {
mStacker[position] = new FragmentStacker();
ft.add(container.getId(), mStacker[position]);
} else {
ft.attach(mStacker[position]);
}
res = mStacker[position];
ft.commit();
return res;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
#Override
public int getCount() {
return 7;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return ((Fragment) object).getView()==view;
}
}}
FragmentStacker:
public class FragmentStacker extends Fragment {
Fragment[] fragments = createFragments();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.task_list_activity_fragment, container, false);
FragmentManager fm = getFragmentManager();
Fragment customDateFragment = fm.findFragmentById(R.id.custom_date_fragment_container);
Fragment taskListFragment = fm.findFragmentById(R.id.task_list_fragment_container);
Fragment bottomPanelFragment = fm.findFragmentById(R.id.bottom_panel_container);
FragmentTransaction fragmentTransaction = fm.beginTransaction();
if (customDateFragment == null) {
customDateFragment = fragments[0];
taskListFragment = fragments[1];
bottomPanelFragment = fragments[2];
fragmentTransaction.add(R.id.custom_date_fragment_container, customDateFragment);
fragmentTransaction.add(R.id.task_list_fragment_container, taskListFragment);
fragmentTransaction.add(R.id.bottom_panel_container, bottomPanelFragment);
fragmentTransaction.commit();
} else {
fragmentTransaction.attach(customDateFragment);
fragmentTransaction.attach(taskListFragment);
fragmentTransaction.attach(bottomPanelFragment);
}
return v;
}
private Fragment[] createFragments() {
return new Fragment[]{new CustomDateFragment(), new TaskListFragment(), new BottomPanelFragment()};
}}
As the title says, I am trying to access (setText,etc) a TextView thats inside a fragment. The fragment is loaded into a viewpager in an activity. I want to access this TextView from the activity class.
private PagerAdapter mPagerAdapter;
private ViewPager pager;
FragmentPageOne fragPageOne;
FragmentPageTwo fragPageTwo;
Exert of Activity's onCreate:
fragPageOne= new FragmentPageOne();
fragPageTwo = new FragmentPageTwo();
mPagerAdapter = new ViewPagerAdapter(this, getSupportFragmentManager(),
fragPageOne.getClass(), fragPageTwo.getClass(),
);
pager = (ViewPager) findViewById(R.id.eventPager);
pager.setAdapter(mPagerAdapter);
ViewPagerAdapter class:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Class<? extends Fragment>> fragmentsClasses;
private final Context context;
public EventViewPagerAdapter(Context context, FragmentManager fm, Class<? extends Fragment>... fragmentsClasses) {
super(fm);
this.context = context;
this.fragmentsClasses = Arrays.asList(fragmentsClasses);
}
public Fragment getItem(int position) {
return Fragment.instantiate(context, fragmentsClasses.get(position).getName());
}
#Override
public int getCount() {
return fragmentsClasses.size();
}
}
FragmentPageOne class (FragmentPageTwo's structure is similar.):
public class FragmentPageOne extends Fragment {
public View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(container == null) {
return null;
}
rootView = inflater.inflate(R.layout.fragment_page_1, container, false);
return (LinearLayout) rootView;
}
}
I am getting a null pointer (obviously) when i try to use this (within the activity itself):
TextView text = (TexView) pager.findViewById(R.id.textview1);
text.setText("hello world);
get your current fragment :
public Fragment getVisibleFragment(){
FragmentManager fragmentManager = this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
if(fragments != null){
for(Fragment fragment : fragments){
if(fragment != null && fragment.isVisible())
return fragment;
}
}
return null;
}
then get the view of the fragment to use findViewById from this view.
You're best bet is to do this in the instantiateItem override method in the pager adapter like so;
private LayoutInflater layoutInflater;
private Activity activity;
private int[] layouts;
public WalletViewPagerAdapter(int[] layouts , Activity activity) {
this.activity = activity;
this.layouts =layouts;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
if (position ==0) {
TextView availableBalance = view.findViewById(R.id.available);
availableBalance.setText("N100,0000,000");
}
container.addView(view);
return view;
}
The view you're trying to access is not yet available as at the time you're calling it. Try overriding the onViewCreated method then use the view parameter to get textView like so;
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
TextView availableBalance = view.findViewById(R.id.available);
availableBalance.setText("N100,0000,000");
}
I am using ViewPager in my activity and it only has two fragments, both implemented in similar structure as follow, so there should always be a fragment returned when getInstanced is called:
public class ListReminderFragment extends Fragment {
private View rootView;
private static ListReminderFragment listReminderFragment;
public static ListReminderFragment getInstance() {
if(listReminderFragment != null)
return listReminderFragment;
else {
listReminderFragment = new ListReminderFragment();
return listReminderFragment;
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.content_main_screen, container, true);
return rootView;
}
#Nullable
#Override
public View getView() {
return rootView;
}
}
This is my adapter:
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ListReminderFragment.getInstance(); // temporary
}
#Override
public int getCount() {
return 2;
}
}
And I am initialising my ViewPager as below, in OnCreate() in the activity that has the ViewPager:
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
ViewPager viewPager = (ViewPager) findViewById(R.id.main_view_pager);
viewPager.setAdapter(viewPagerAdapter);
But when I call viewPager.getChildAt(), viewPagerAdapter.getItem(0).getView(), they both return null,
when I call viewPager.getChildCount(), it returns 0 instead of 2.
How should I access the views in side the fragment in ViewPager?
This is my first time trying to implement a ViewPager. My app basically has a listing and details page and I'd like the user to be able to swipe between the details. The details are based on an id that I pass in from the listing page. The problem is that I'm calling getActivity() in the details fragment, which is coming back null. Like I said, I'm new to implementing a ViewPager so this might be something obvious:
ListingFragment.class:
public class ListingFragment extends SherlockFragmentActivity
{
private ViewPager mViewPager;
private MyFragmentPagerAdapter mMyFragmentPagerAdapter;
private static List<Fragment> fragments;
public int Id = 0;
#Override
public void onCreate(final Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
mViewPager = (ViewPager)findViewById(R.id.viewpager);
mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mMyFragmentPagerAdapter);
DetailsFragment df1 = new DetailsFragment();
df1.Id = 1;
df1.DisplayItems();
fragments.add(lf);
DetailsFragment df2 = new DetailsFragment();
df2.Id = 2;
df2.DisplayItems();
fragments.add(lf);
}
private static class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
return fragments.get(index);
}
#Override
public int getCount() {
return 2;
}
}
}
DetailsFragment.class
public class DetailsFragment extends SherlockFragmentActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(final Bundle icicle)
{
super.onActivityCreated(icicle);
}
private void DisplayItems()
{
PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("value", false);
...
}
}
UPDATE
I've updated my code to use static newInstance method and a Bundle to pass the id to the details fragment.
ListingFragment.class:
public class ListingFragment extends SherlockFragmentActivity
{
private ViewPager mViewPager;
private MyFragmentPagerAdapter mMyFragmentPagerAdapter;
private static List<Fragment> fragments;
public int Id = 0;
#Override
public void onCreate(final Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
mViewPager = (ViewPager)findViewById(R.id.viewpager);
mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mMyFragmentPagerAdapter);
DetailsFragment df1 = DetailsFragment.newInstance(1);
fragments.add(df1);
DetailsFragment df2 = DetailsFragment.newInstance(2);
fragments.add(df2);
}
private static class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
return fragments.get(index);
}
#Override
public int getCount() {
return 2;
}
}
}
DetailsFragment.class
public class DetailsFragment extends SherlockFragmentActivity
{
private int detailId;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(final Bundle icicle)
{
super.onActivityCreated(icicle);
}
public static DetailsFragment newInstance(int id) {
DetailsFragment lf = new DetailsFragment();
Bundle bundle = new Bundle();
bundle.putInt("id", id);
lf.setArguments(bundle);
return lf;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.listing, container, false);
detailId = getArguments().getInt("id");
DisplayItems();
return view;
}
private void DisplayItems()
{
PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("value", false);
...
}
}
You shouldn't be setting variables and calling methods that have to do with initialization from the activity like that.Id should be set using setArguments(...) and using a static newInstance(...) method to instantiate your fragment. You should call displayItems() in onCreateView(...) inside your Fragment, not from the attached Activity.
See the official Android guide on Fragments for more information. You definitely should give the whole thing a read. http://developer.android.com/guide/components/fragments.html
I'm trying to use a ListFragment with a ViewPager using the FragmentPagerAdapter. The pager consists of two instances of the ListFragment. The ViewPager control works and allows me to swipe between the fragments however the same ListFragment appears in both pages. It seems that getItem() method of the ViewPager creates two different instances of the ListFragment but it displays only the second instance of it for both pages. Here is a code:
// FragmentPagerAdapter
private static class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
Log.i("Page: ", index + "");
return PageFragment.newInstance(pages.get(index));
// pages is an ArrayList<ArrayList<Restaurant>> pages
}
#Override
public int getCount() {
return numberOfPages;
}
}
// ListFragment
public class PageFragment extends ListFragment {
private static ArrayList<Restaurant> restaurantsList;
public static PageFragment newInstance(ArrayList<Restaurant> restaurantsList) {
PageFragment pageFragment = new PageFragment();
pageFragment.setRestaurantsList(restaurantsList);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
setListAdapter(new RestaurantArrayAdapter(getActivity().getBaseContext(), getRestaurantsList()) );
return view;
}
private void setRestaurantsList(ArrayList<Restaurant> list)
{
restaurantsList = list;
}
private ArrayList<Restaurant> getRestaurantsList()
{
return this.restaurantsList;
}
}
Well mate,
The problem is you've declared you array member as "Static",
private static ArrayList<Restaurant> restaurantsList;
Lose the static and you should be fine.