Display ViewPager in fragment of my mainActivity - android

I am a new member here.
I have already done several searches for two days on my problem but I have not found anything.
So I invite you to ask for help.
I have a navigation drawer This is a category I would like to put a fragment that when I slip left or right, my calendar appears with a different date.
So I developed a ViewPager in a fragment. This fragment is a fragment for my navigation drawer.
My problem: The ViewPage does not appear.
Either it is the page viewer that is displayed either it is a blank fragment.
It is the line of code who change the display :
mContext.setContentView(ViewPager);
screen without this code
screen with this code
The number "89" is a random number who is incremented by 1 on swipe.
The differents part code :
in the main acitivity to show fragment:
TestSlideFragment fragment = new TestSlideFragment();
fragmentTransaction.replace(R.id.RelativeLayout_for_Fragment, fragment, fragment.getTag());
fragmentTransaction.commit();
testSlideFragment (java and xml)
public class TestSlideFragment extends Fragment {
View view = null;
private static final int NUM_PAGES = 5;
int nbr = 0 ;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
ViewPager ViewPager;
FragmentStatePagerAdapter mAdapt;
//private TabsAdapter d;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
public TestSlideFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_test_slide, container, false);
return view;
}
/**
* The number of pages (wizard steps) to show in this demo.
*/
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Activity mActivity = getActivity();
FragmentActivity mContext;
mContext=(FragmentActivity) mActivity;
ViewPager = new ViewPager(mContext);
ViewPager.setId(R.id.slide);
mContext.setContentView(ViewPager);
mPagerAdapter = new ScreenSlidePagerAdapter(mContext.getSupportFragmentManager());
ViewPager.setAdapter(mPagerAdapter);
ViewPager.setCurrentItem(1);
}
/**
* A simple pager adapter that represents 5 ScreenSlidePageFragment objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new ScreenSlidePageFragment();
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
XML:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:tag="fragment_test_slide"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="oytoch.iut_info.test.TestSlideFragment">
<!-- TODO: Update blank fragment layout -->
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/page"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
ScreenSlidePageFragment
public class ScreenSlidePageFragment extends Fragment {
ViewGroup rootView = null;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_screen_slide_page,container,false);
return rootView;
}
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Activity mActivity = getActivity();
Context mContext = getActivity();
TextView slide_txt = (TextView) rootView.findViewById(R.id.slide);
SharedPreferences prefs = mContext.getSharedPreferences(MyPREFERENCES , MODE_PRIVATE);
int restoredText = prefs.getInt("nbr", 0);
slide_txt.setText(Integer.toString(restoredText));
sharedpreferences = mContext.getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("nbr", 1+ restoredText);
editor.commit();
}
}
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<ScrollView
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView`enter code here`
android:padding="16dp"
android:id="#+id/slide"
android:lineSpacingMultiplier="1.2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="lorem_ipsum" />
</ScrollView>
</FrameLayout>
How do I display this page viewer in my main activity?
Thanks for reading me

Inside your TestSlideFragment replace below code which you have written inside onActivityCreated
ViewPager = new ViewPager(mContext);
ViewPager.setId(R.id.slide);
mContext.setContentView(ViewPager);
with
ViewPager = (ViewPager)getView().findViewById(R.id.page);
And try to run your application again.

Why are you adding the viewpager in the setcontentview method? That sets the viewpager for the whole activity.
Find your viewpager within the fragment like
vp = (ViewPager) view.findViewById(R.id.viewpager).

Related

How to replace the first Fragment of ViewPager with another Fragment and be at the same position of the previous Fragment

I'm using TabLayout and ViewPager in my app . I have 2 tabs in my ViewPager . I have the main 2 Fragment for the 2 tabs .
The first Fragment is like a form when user click submit , another Fragment appears to user and so on and be at the same position of the previous Fragment. I want to do that in the first Fragment (first position of my ViewPager) and keep the state of the previous fragment when I click back button . I hope that I posted my question in a right way
Here is my ViewPager
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
tools:context=".UI.Fragments.OnlineBookingModule.OnlineBookingFragment">
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tabLayout"
app:tabIndicatorColor="#color/colorPrimary"
android:background="#color/bg_nav"/>
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/viewPager"/>
</LinearLayout>
Here is My Pager Adapter
public class BookingPagerAdapter extends FragmentStatePagerAdapter {
private Context context;
public BookingPagerAdapter(#NonNull FragmentManager fm, int behavior,Context context) {
super(fm, behavior);
this.context=context;
}
#NonNull
#Override
public Fragment getItem(int position) {
if(position==0)
return new NewBookingFragment();
else
return new FutureBookingFragment();
}
#Override
public int getCount() {
return 2;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
if(position==0)
return context.getString(R.string.new_booking);
else
return context.getString(R.string.future_booking);
}
}
Here is how I setup my viewPager in my Fragment
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_online_booking, container, false);
tabLayout = view.findViewById(R.id.tabLayout);
viewPager = view.findViewById(R.id.viewPager);
Preferences preferences = new Preferences();
preferences.saveSmallDays(getActivity(),0);
preferences.saveBigDays(getActivity(),0);
assert getFragmentManager() != null;
pagerAdapter = new BookingPagerAdapter(getFragmentManager(), FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT,getActivity());
tabLayout.setupWithViewPager(viewPager);
viewPager.setAdapter(pagerAdapter);
return view;
}

How to add button and a processing layout on android studio

I'm a student in 2 year electrical and computer science : i am not familiar with android studio (most of the time i work on C++).
I made a joystick on processing for an android project, and then I exported my processing sketch to android studio, now I have to find a way to recover data (vector position) from my processing sketch to my main activity.
BUT here is the problem:
I want to add a TextView to my main activity but the processing sketch takes all the window, and I can't reduce it.
so what did i try :
I tried to place the fragment in a relative layout, and then place the TextView but it didn't work, even if i make the fragment very little it still taking the whole screen.
My thought are that there is a problem with this line ->
setContentView(frame, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
I made some screenshots:
Here the Main Activity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout frame = new FrameLayout(this);
frame.setId(CompatUtils.getUniqueViewId());
setContentView(frame, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
// setContentView(R.layout.main); // attach the view for this activity
sketch = new Joystick();
PFragment fragment = new PFragment(sketch);
fragment.setView(frame, this);
}
Here the view of the main activity
In order to have a fragment in your Main Activity you can do the following:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.*/
ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
private class YourFragmentAdapter extends FragmentPagerAdapter {
SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new YourFragment()
default:
return null;
}
}
#Override
public int getCount() {
return 1;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Your fragment name";
}
return null;
}
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Your fragment class:
public class YourFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
In this way you could have an activity with as many views as you want, and as many fragments as you wish. Note that if you have more than one fragment your activity will be more like a tabbed activity.

How to implement a Viewpager with tabstrip inside a fragment?

hello Friends i am little new to this Fragments concept!
Problem is
I am having a Actionbar with tabs and fragments now I want to implement viewpager inside one of the fragment of Actionbar tabs.
the point is to implement View pager with tabstrip inside a fragment
Please help me!
I hope that will be useful at least for anyone with the same problem if not for you.
You can put this fragment in every tab from action bar. The code is:
public class TabFragment extends Fragment {
ViewPager mViewPager;
DemoCollectionPagerAdapter mPagerAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab, container, false);
mPagerAdapter = new DemoCollectionPagerAdapter(getChildFragmentManager());
// Set up the ViewPager, attaching the adapter.
mViewPager = (ViewPager) view.findViewById(R.id.view_pager);
mViewPager.setAdapter(mPagerAdapter);
return view;
}
}
I took PagerAdapter from the Effective Navigation example and just removed the "static" attribute in order to move it in the separate file:
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1); // Our object is just an integer :-P
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// For this contrived example, we have a 100-object collection.
return 5;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
Integer.toString(args.getInt(ARG_OBJECT)));
return rootView;
}
}
}
And the fragment_tab.xml for this TabFragment is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.PagerTabStrip android:id="#+id/pager_tab_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:textColor="#fff"
android:paddingTop="4dp"
android:paddingBottom="4dp" />
</android.support.v4.view.ViewPager>
Consider using a PagerTabStrip as a child view of ViewPager if you want the tab headers to be clickable and a PagerTitleStrip for them to be static (user can only swipe in order to switch to the tab).
Depending on your implementation of ActionBar with tabs I suppose there can arise some dependency problems because in this example I've used support library.

recreate view of fragment via button

I've got a FragmentActivity which show the correct fragment, using a ViewPager. I added a Fragment StatePagerAdapter to the ViewPager. If I push a button at a Fragment, it should be recreated (onCreateView should be called again). The fragments are articles and if the user is offline, I'll show him "please check your networkconnection" and a button to reload. The button called a method in the FragmentActivity, but I don't know how implement it. Maybe I can destroy and recreate the current Fragment?
here the important part of the FragmentActivity:
private ArrayList<Fragment> fragments;
protected void onCreate(Bundle savedInstanceState)
{
context = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_article_page_slider);
...
pages = datahandler.getCount(...);
viewPager = (ViewPager) findViewById(R.id.articlePager);
PagerAdapter pagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(startPosition);
fragments = new ArrayList<Fragment>(pages);
}
public void reloadData(View v)
{
// TODO
((ArticlePageFragment)fragments.get(viewPager.getCurrentItem())).refresh();
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter
{
public ScreenSlidePagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
Fragment fragment = new ArticlePageFragment();
Bundle args = new Bundle();
...
fragment.setArguments(args);
fragments.add(position, fragment);
return fragment;
}
public int getCount()
{
return pages;
}
}
and the Fragment itself:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
activity = getActivity();
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_article_page, container, false);
CacheDataHandler cdh = new CacheDataHandler(activity);
cdh.open();
String htmlData = cdh.loadData();
rootView.findViewById(R.id.btn_reload_article_data).setVisibility(View.GONE);
webView = ((WebView) rootView.findViewById(R.id.articleFragment));
refresh();
...
return rootView;
}
public void refresh()
{
...
if (htmlData == null)
{
rootView.findViewById(R.id.btn_reload_article_data).setVisibility(View.VISIBLE);
webView.loadData(defaultdata,"text/html", "UTF-8");
}
else
{
webView.loadData(htmlData,"text/html", "UTF-8");
}
}
and the fragment_article_page.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<WebView
android:id="#+id/articleFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<Button
android:id="#+id/btn_reload_article_data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="reloadData"
android:text="#string/btn_txt_reload_data"
android:visibility="gone" />
</RelativeLayout>
EDIT
added a private ArrayList<Fragment> fragments in FragmentActivity and transfer the code for manipulating the view in an extra refreshMethod, look ahead. All works fine, if I only click on the first or second Fragment (index 0 and 1). Otherwise I get an IndexOutOfBoundsException. How to initialize and fill the ArrayList?

ViewPager with Fragment with different layouts

I am new to using ViewPagers and Fragments together. My app has a ListView on startup, which bring the user to a details view based on a id that is passed. The problem I'm running into is that the details view has a different layout then the list view. The ViewPager is on the intial screen's layout, so when using the ViewPager the layout retains the inital layout, which is basically just a status bar at the bottom, which should go away when the user is on the details view.
This is what I have so far:
Main.xml (initial layout on startup, with a status bar)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
>
<!-- Footer -->
<TextView
android:id="#+id/status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
/>
<!-- Footer -->
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_above="#id/status
/>
</RelativeLayout>
Main.class
public class Main extends SherlockFragmentActivity
{
private static int NUMBER_OF_PAGES;
private ViewPager mViewPager;
private MyFragmentPagerAdapter mMyFragmentPagerAdapter;
private static List<Fragment> fragments;
#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);
NUMBER_OF_PAGES = 5;
fragments = new ArrayList<Fragment>();
fragments.add(new ListingFragment()); //initial screen that just a ListView
fragments.add(DetailsFragment.newInstance(1));
fragments.add(DetailsFragment.newInstance(2));
fragments.add(DetailsFragment.newInstance(3));
fragments.add(DetailsFragment.newInstance(4));
}
private static class MyFragmentPagerAdapter extends FragmentStatePagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
return fragments.get(index);
}
#Override
public int getCount() {
return NUMBER_OF_PAGES;
}
}
}
Details.xml (details view with no status bar)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
/>
</RelativeLayout>
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.details, container, false);
detailId = getArguments().getInt("id");
return view;
}
}
The ViewPager is on the intial screen's layout, so when using the
ViewPager the layout retains the inital layout, which is basically
just a status bar at the bottom, which should go away when the user is
on the details view.
Then don't put it in the main layout file. If the status is tied to the first fragment then it belong in its view, especially if the DetailsFragment doesn't need to show that status TextView.
So remove the status TextView from main.xml and add it to the layout file used in the ListingFragment. If ListingFragment extends ListFragment then create a layout file which contains a ListView with the id(android:id="#android:id/list") + the status TextView and inflate this layout file in the onCreateView.

Categories

Resources