I'm trying to use the Fragment, ViewPager & co. from the Android support library v4. Fragments seem to scroll when I listen to page change events from the pager but the content is not visible. What I basically have is:
A FragmentActivity:
public class MyActivity extends FragmentActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FragmentPagerAdapter fpa = new MyPagerAdapter(this, createFragments());
ViewPager vp = (ViewPager) findViewById(R.id.pager);
vp.setAdapter(fpa);
}
private List<Fragment> createFragments() {
List<Fragment> list = new ArrayList<Fragment>();
list.add(Fragment.instantiate(this, First.class.getName()));
list.add(Fragment.instantiate(this, Second.class.getName()));
list.add(Fragment.instantiate(this, Third.class.getName()));
return list;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
}
A FragmentPagerAdapter:
public class MyPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPagerAdapter(FragmentActivity activity, List<Fragment> fragments) {
super(activity.getSupportFragmentManager());
this.fragments = fragments;
}
#Override
public Fragment getItem(int i) {
return fragments.get(i);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public boolean isViewFromObject(View view, Object o) {
return view.equals(o);
}
}
And three Fragments that look like this:
public class First extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.first, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
And they have layout like these:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:text="First Fragment"
android:id="#+id/firstText"/>
</LinearLayout>
I originally forgot to add the main layout, here it comes:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_width="fill_parent"/>
</LinearLayout>
I would appreciate if someone can tell me what I am doing wrong.
This is because you have overridden isViewFromObject in MyPagerAdapter.
FragmentPagerAdapter handles isViewFromObject, so you shouldnt override it.
As with me, I reckon most visitors to this post started with a basic PagerAdapter, then realised they needed to page fragments and changed their base class without realising the consequences. Unfortunate, but I couldn't criticise the Android team for this.
Ya correct as Ian Newson told, just remove isViewFromObject overrided method from your code
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
Related
I've been recently working on a project and I have tried using ViewPager for the first time. Unfortunately, something is not going as expected. I have created my ViewPagerAdapter:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragmentList = new ArrayList<>();
private List<String> stringList = new ArrayList<>();
public ViewPagerAdapter(#NonNull FragmentManager fm) {
super(fm);
}
public ViewPagerAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
#NonNull
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return stringList.get(position);
}
public void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
stringList.add(title);
}
There are multiple fragments handled in the activity by the adapter.
public class PatientActivity extends AppCompatActivity {
#BindView(R.id.tab_layout)
TabLayout tabLayout;
#BindView(R.id.view_pager_pacient_view)
ViewPager viewPager;
ActivityPatientBinding binding;
ViewPagerAdapter viewPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityPatientBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
ButterKnife.bind(this);
setupViewPager();
}
private void setupViewPager() {
//getChildFragmentManager?
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragment(PatientDetailsFragment.newInstance(), "Pacient");
viewPagerAdapter.addFragment(StateFragment.newInstance(), "Stare");
viewPagerAdapter.addFragment(PathologicalBackgroundFragment.newInstance(), "Antecedente");
viewPagerAdapter.addFragment(TriageFragment.newInstance(), "Triaj");
viewPagerAdapter.addFragment(EkgFragment.newInstance(), "Observatii");
viewPagerAdapter.addFragment(AnalysisFragment.newInstance(), "Analize");
viewPagerAdapter.addFragment(RecommendationFragment.newInstance(), "Recomandari");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
}
}
And the xml belonging to the activity is this one
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="?android:windowBackground"
tools:context=".ui.addpatientpage.PatientActivity"
android:orientation="horizontal">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:theme="#style/AppTheme.AppBarOverlay"
app:elevation="0dp">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:paddingHorizontal="#dimen/spacing_medium"
app:tabBackground="#android:color/transparent"
app:tabGravity="center"
app:tabIndicator="#drawable/shape_rounded_red"
app:tabIndicatorColor="#color/colorNavigation"
app:tabIndicatorGravity="center"
app:tabIndicatorHeight="#dimen/spacing_xlarge"
app:tabMinWidth="120dp"
app:tabRippleColor="#android:color/transparent"
app:tabSelectedTextColor="#android:color/white"
app:tabTextAppearance="#style/TextAppearance.AppCompat.Body2"
app:tabTextColor="#color/grey_60">
</com.google.android.material.tabs.TabLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager_pacient_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
sample of the Fragment:
public class PatientDetailsFragment extends Fragment {
public static PatientDetailsFragment newInstance() {
return new PatientDetailsFragment();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.row_pacient_details, container, false);
ButterKnife.bind(this, root);
return root;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
Should I override the method onViewCreated in each fragment to make the visible?
I have looked at the code multiple times and tried different solutions, I have even tried to implement it with ViewPager2, but nothing seems to work. It feels like there is a small fix that is needed, but after many hours of trying, I came to the conclusion that I can not find it by myself. Can you please also take a look and eventually give me a hint? Should I override the method onViewCreated in each fragment to make the visible or do you see some other issue in here?
If the adapter seems to contain all of the fragments specified in the main class, where can it go wrong?
I made an application extending an activity, all worked fine.
To improve the application I changed the activity to Fragment (using onCreateView , onActivityCreated), but now all the images not shown.
I don't get any errors.
I open the Fragments inside the FragmentActivity using FragmentStatePagerAdapter.
Is there something I'm missing ?
Fragment XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent" android:layout_height="match_parent"
android:padding="10dp"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="170dp"
android:maxWidth="170dp"
android:minHeight="170dp"
android:maxHeight="170dp"
app:srcCompat="#drawable/logo_pic"
android:id="#+id/iv_profile_img"
android:layout_below="#+id/relativeview_search_bar"
android:layout_centerHorizontal="true"
android:layout_marginTop="12dp"
android:background="#drawable/circle_image"
/>
</RelativeLayout>
Fragment Class:
public class TempActivity extends Fragment {
private static final String TAG = "SearchCars";
ArrayList<ListUser> userChatItems;
MessagesAdapter mAdapter;
FragmentActivity con;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_listview_users_profiles, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//con = this.getContext();
con = this.getActivity();
Log.v(TAG, "Initializing ...");
View v = getView();
}
}
PageAdapter:
public class PageAdapter extends FragmentStatePagerAdapter {
public PageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new MyProfileActivity();
default:
break;
}
return null;
}
#Override
public int getCount() {
return 1;
}
}
Main Fragment Activity:
public class MainFragmentActivity extends FragmentActivity{
ViewPager viewpager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_fragment);
viewpager = (ViewPager) findViewById(R.id.pager);
PageAdapter pageAdapter = new PageAdapter(getSupportFragmentManager());
viewpager.setAdapter(pageAdapter);
}
}
Well I found that if I change to android:src instead of app:srcCompat
all is working fine.
It's probably better to use app:secCompat when extending from AppCompatActivity
But, when I use Fragment it doesn't work any more.
I have a TabLayout and ViewPager to hold and navigate between my fragments (3 of them) and that is working fine however I'm getting confused as to how I interact with each fragment for example button clicks or edit texts. Here is my main activity xml.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.design.widget.TabLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/tabLayout"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#color/colorPrimary"
app:tabMode="fixed"
app:tabGravity="fill" />
<android.support.v4.view.ViewPager
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/viewPager"
android:layout_centerHorizontal="true"
android:layout_below="#+id/tabLayout" />
</RelativeLayout>
This is the activity for it.
public class ActivityMain extends AppCompatActivity {
private String tabTitles[] = new String[] { "contacts", "home", "search" };
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(new CustomAdapater(getSupportFragmentManager(),getApplicationContext()));
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
});
}
private class CustomAdapater extends FragmentPagerAdapter {
private String fragments [] = {"contacts", "home", "search"};
public CustomAdapater(FragmentManager supportFragmentManager, Context applicationContext) {
super(supportFragmentManager);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new FragmentContacts();
case 1:
return new FragmentMain();
case 2:
return new FragmentSearch();
default:
return null;
}
}
#Override
public int getCount() {
return fragments.length;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
}
And here is a fragment activity.
public class FragmentSearch extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.fragment_search,container,false);
}
}
Now say in my R.layout.fragment_search I had a button just for examples sake, how do I set an onclicklistener for it? Is it within the FragmentSearch or ActivityMain? I've searched around but I'm just getting more confused.
You'd set your onClickListener in the fragment's onCreateView method by doing something like:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
myButton = (Button) rootView.findViewById(R.id.buttonId);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
return rootView;
}
Everything is the same regarding the onClickListener, as you can see. The only difference is that you have to inflate to view and use that view to find the appropriate components (e.g. buttons, textviews..)
Now, if you want to communicate between Fragments, you will need to implement more things. The basic way is to use interfaces to be implemented by your activity, so each fragment can call those methods within the activities.
There are also messaging libraries such as Otto and EventBus, they are great by sending stuff between not just fragments, but services also.
The following is layout
test.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Click"
android:id="#+id/button"
/>
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
test_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Hello"
android:id="#+id/textView" android:layout_gravity="center_horizontal"/>
</LinearLayout>
common_view_pager_layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/MainViewerPage"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<android.support.v4.view.PagerTabStrip
android:id="#+id/TitlePageTabStrip"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.v4.view.ViewPager>
</LinearLayout>
The following is my Activity code
public class TestFragmentActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.test);
Button button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, new HomeFragment()).commit();
}
});
}
public class HomeFragment extends Fragment {
private PagerAdapter _adapter;
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.common_view_pager_layout, container, false);
this._adapter = new PagerAdapter(TestFragmentActivity.this);
this._adapter.add(new DetailFragment());
ViewPager pager = (ViewPager) view.findViewById(R.id.MainViewerPage);
pager.setAdapter(this._adapter);
return view;
}
}
public class DetailFragment extends Fragment {
public DetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.test_detail, container, false);
return rootView;
}
}
public class PagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> _fragments;
public PagerAdapter(FragmentActivity activity) {
super(activity.getSupportFragmentManager());
this._fragments = new ArrayList<Fragment>();
}
public void add(Fragment fragment) {
this._fragments.add(fragment);
}
#Override
public Fragment getItem(int position) {
return this._fragments.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
return "Test";
}
#Override
public int getCount() {
return 1;
}
}
}
When I click a button the fragment in ViewPager was display
But when I click the button again the fragment disappear
Please help me.
try using this:
in the constructor of your adapter change this :
public class MyPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> _fragments;
public MyPagerAdapter(FragmentManager activity) {
super(activity);
this._fragments = new ArrayList<Fragment>();
}
public void add(Fragment fragment) {
this._fragments.add(fragment);
}
#Override
public Fragment getItem(int position) {
return this._fragments.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
return "Test";
}
#Override
public int getCount() {
return 1;
}
}
and when you want to create the adapter send getChildFragmentManager() to its constructor
public class HomeFragment extends Fragment {
private MyPagerAdapter _adapter;
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.common_view_pager_layout, container, false);
ViewPager pager = (ViewPager) view.findViewById(R.id.MainViewerPage);
this._adapter = new MyPagerAdapter(getChildFragmentManager());
this._adapter.add(new DetailFragment());
pager.setAdapter(this._adapter);
return view;
}
}
I test it and it works, any problem comment it.
Good Luck!
In your Fragment class, in the onCreate() method, you have to call setRetainInstance(true) like this:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
This tells the FragmentManager to keep your fragments on reloads.
In addition, check your manifest file doesn't have any
android:screenOrientation
config changes where you are basically saying you will handle reloads due to config changes yourself.
In PagerFragment 's onResume() add this:
#Override
public void onResume() {
super.onResume();
for (Fragment fragment : getFragmentManager().getFragments()) {
if (fragment instanceof Tab1Fragment || fragment instanceof Tab2Fragment) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(fragment);
ft.attach(fragment);
ft.commit();
}
}
}
Try to add this lines in your code:
public int getItemPosition(Object object) {
return POSITION_NONE;
}
and Add the below lines
pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
... anything you may need to do to handle pager state ...
adapter.notifyDataSetChanged(); //this line will force all pages to be loaded fresh when changing between fragments
}
Under
pager.setAdapter(adapter);
Hope this may help you!
Ensure you pass the adapter instance the child fragment manager, not the fragment manager.
Like this:
this._adapter = new PagerAdapter(getChildFragmentManager());
I am trying to get a fragment with three tabs displayed using ViewPager. Initially I used to instantiate the fragment from the Activity using FragmentMgr, this worked fine. When I converted this navigation using ViewPager, this Fragment is no longer displayed.
MainActivity.java
When I initiate Fragment like this, it gets displayed. eg:
LaunchListFragment fragment = new LaunchListFragment();
fragment.newInstance(LIST_TYPE);
getSupportFragmentManager().beginTransaction()
.add(R.id.item_detail_container,
fragment).commit();
I tried this change above code to make use of ViewPager as follows:
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(new LaunchPageAdapter(getSupportFragmentManager(),LIST_TYPE));
mViewPager.setCurrentItem(0);
where LaunchPageAdapter calls LaunchListFragment.
LaunchPageAdapter.java
public class LaunchPageAdapter extends FragmentPagerAdapter {
private static String select="";
public LaunchPageAdapter(FragmentManager fm, String type) {
super(fm);
select=type;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return LaunchListFragment.newInstance(select);
case 1:
return AddTeamFragment.newInstance();
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 2;
}
Here is LaunchListFragment.java
public class LaunchListFragment extends ListFragment implements ActionBar.TabListener {
public static String LIST_TYPE = "invalid";
GenericListData g_data[] = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View result = inflater.inflate(R.layout.fragment_launch_list,
container, false);
setActionTabs();
setList();
return (result);
}
public static Fragment newInstance(String type) {
Fragment frag = new LaunchListFragment();
Bundle args = new Bundle();
LIST_TYPE=type;
args.putString(LIST_TYPE, type);
frag.setArguments(args);
return (frag);
}
This is main.xml layout used by MainActivity
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools= "match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:baselineAligned="false"
android:divider="?android:attr/dividerHorizontal"
android:orientation="horizontal"
android:showDividers="middle"
tools:context=".MainActivity" >
<fragment
android:id="#+id/item_list"
android:name="com.teammanager.ItemListFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
tools:layout="#android:layout/list_content" />
<FrameLayout
android:id="#+id/item_detail_container"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</FrameLayout>
fragment_launch_list.xml used by LaunchListFragment
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:drawSelectorOnTop="false" >
</ListView>
<TextView
android:id="#+id/itemName"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical"
android:textColor="#000000"
android:textSize="22dp"
android:textStyle="bold" />
When I debug this, I can see LaunchListFragment is getting instantiated, onCreate and onCreate View is called, it just won't get displayed. :(
Can anyone here let me know if I am missing anything here in my ViewPager implementation?
Update
When I called LaunchListFragment without using Viewpager, I set the content view first and passed R.id.item_detail_container which is the id of the FrameLayout where I want the fragment to be displayed. Please refer to main.xml earlier
setContentView(R.layout.main.xml);
LaunchListFragment fragment = new LaunchListFragment();
fragment.newInstance(LIST_TYPE);
getSupportFragmentManager().beginTransaction()
.add(R.id.item_detail_container,
fragment).commit();
When I changed this to use ViewPager, I am not sure where I'm directing the Fragment to be displayed. In my fragment onView I'm inflating fragment_launch_list and returning the View. But how will the view pager know where to set the fragment view. Is it inside the id pager?
I'm an absolute beginner, I apologize if all these are naive questions.
Cheers.
The question description is perfectly suitable to the problem I just had. I know the question is old but may this help other who face same. #Geoplex have not shown code of LaunchPageAdapter class. So I'm not sure if this solves his problem or not. But for me that worked.
In my PagerAdapter, the
public boolean isViewFromObject(View view, Object object) was overridden. I removed that method and allowed superClass to handle it. That started giving my expected result.
This is useful for you,
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments=null;
private FragmentManager fragmentManager=null;
public ViewPagerAdapter(FragmentManager fragmentManager,List<Fragment> fragments) {
super(fragmentManager);
this.fragments=fragments;
this.fragmentManager=fragmentManager;
}
#Override
public Fragment getItem(int position) {
fragmentManager.beginTransaction().commitAllowingStateLoss();
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object)
{
super.setPrimaryItem(container,0,fragments.get(0));
}
#Override
public void notifyDataSetChanged()
{
super.notifyDataSetChanged();
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
fragmentManager.executePendingTransactions();
fragmentManager.saveFragmentInstanceState(fragments.get(position));
}
public void replaceItem(int position,Fragment fragment)
{
fragments.set(position, fragment);
this.notifyDataSetChanged();
}
}
MainActivity.java
public class MainActivity extends FragmentActivity implements OnPageChangeListener,TabListener
{
private android.support.v4.view.ViewPager mViewPager=null;
private ViewPagerAdapter mPagerAdapter=null;
private ActionBar action=null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
initilizeViewPager();
action=getActionBar();
action.setDisplayShowHomeEnabled(false);
action.setDisplayShowTitleEnabled(false);
action.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
public void initilizeViewPager()
{
mViewPager=(android.support.v4.view.ViewPager)findViewById(R.id.viewPager);
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(LaunchListFragment.newInstance(select));
fragments.add(AddTeamFragment.newInstance());
fragments.add(thirdFragment.newInstance());
viewPagerAdapter=new ViewPagerAdapter();
mViewPager.setAdapter(viewPagerAdapter(getSupportFragmentManager(),fragments));
new setAdapterTask().execute();
mViewPager.setOnPageChangeListener(this);
}
private class setAdapterTask extends AsyncTask<Void,Void,Void>
{
protected Void doInBackground(Void... params)
{
return null;
}
#Override
protected void onPostExecute(Void result)
{
mViewPager.setAdapter(mPagerAdapter);
Tab first=action.newTab().setTag("first").setText("First").setTabListener(MainActivity.this);
Tab second=action.newTab().setTag("second").setText("Second").setTabListener(MainActivity.this);
Tab third=action.newTab().setTag("third").setText("Third").setTabListener(MainActivity.this);
action.addTab(first);
action.addTab(second);
action.addTab(third);
}
}
}
public void onPageScrollStateChanged(int arg0)
{}
public void onPageScrolled(int arg0, float arg1, int arg2)
{}
public void onPageSelected(int position)
{
getActionBar().setSelectedNavigationItem(position);
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {}
}
main_layout.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_below="#android:id/tabs"
android:layout_height="fill_parent"/>
</RelativeLayout>